1use super::{CompactedCheckpoint, ContextEntry, ContextError, SessionContextSnapshot};
2use crate::{
3 memory::{
4 ActivatedMemory, MemoryActivationProvenance, MemoryActivationReason, MemoryActivationScore,
5 MemoryEvidence, MemoryId, MemoryScope,
6 },
7 text,
8 token_estimate::estimate_text_tokens,
9};
10use std::{
11 cmp::Ordering,
12 collections::{BTreeMap, btree_map::Entry},
13};
14
15fn format_memory_scope(scope: MemoryScope) -> &'static str {
16 match scope {
17 MemoryScope::Session => "session",
18 MemoryScope::Task => "task",
19 MemoryScope::Step => "step",
20 }
21}
22
23fn format_memory_scopes(scopes: &[MemoryScope]) -> String {
24 scopes
25 .iter()
26 .map(|scope| format_memory_scope(*scope))
27 .collect::<Vec<_>>()
28 .join(",")
29}
30
31fn canonicalize_memory_reason_text(value: &str) -> String {
32 text::collapse_whitespace(value).to_lowercase()
33}
34
35#[derive(Debug, Default)]
49pub struct ContextCompiler;
50
51impl ContextCompiler {
52 #[must_use]
54 pub fn new() -> Self {
55 Self
56 }
57
58 pub fn compile(
64 &self,
65 snapshot: &SessionContextSnapshot,
66 ) -> Result<CompiledContext, ContextError> {
67 compile_entries(
68 snapshot.entries(),
69 snapshot.memories(),
70 snapshot.compacted_checkpoint(),
71 )
72 }
73
74 pub(crate) fn compile_without_compacted_checkpoint(
75 &self,
76 snapshot: &SessionContextSnapshot,
77 ) -> Result<CompiledContext, ContextError> {
78 compile_entries(snapshot.entries(), snapshot.memories(), None)
79 }
80}
81
82fn compile_entries(
83 entries: &[ContextEntry],
84 memories: &[ActivatedMemory],
85 compacted_checkpoint: Option<&CompactedCheckpoint>,
86) -> Result<CompiledContext, ContextError> {
87 let mut sections = Vec::with_capacity(entries.len());
88
89 for entry in entries {
90 match entry {
91 ContextEntry::Summary(summary) => {
92 sections.push(CompiledContextSection::Summary {
93 id: summary.id().to_owned(),
94 text: summary.text().to_owned(),
95 });
96 }
97 }
98 }
99
100 sections.sort_by(|left, right| left.sort_key().cmp(&right.sort_key()));
101
102 for memory in memories {
103 if memory.item().evidence().is_empty() {
104 return Err(ContextError::MemoryWithoutEvidence {
105 memory_id: memory.item().id().as_str().to_owned(),
106 });
107 }
108 }
109 let mut memory_projection = canonical_memory_projection(memories);
110 memory_projection.sort_by(|left, right| {
111 right
112 .score
113 .cmp(&left.score)
114 .then_with(|| left.id.cmp(&right.id))
115 });
116
117 Ok(CompiledContext {
118 sections,
119 memory_projection,
120 checkpoint: ContextCheckpointSegment::new(compacted_checkpoint.cloned()),
121 })
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct CompiledContext {
130 sections: Vec<CompiledContextSection>,
131 memory_projection: Vec<CompiledMemory>,
132 checkpoint: ContextCheckpointSegment,
133}
134
135impl CompiledContext {
136 #[must_use]
141 pub fn sections(&self) -> &[CompiledContextSection] {
142 &self.sections
143 }
144
145 #[must_use]
150 pub fn to_snapshot(&self) -> String {
151 let mut lines = Vec::new();
152
153 self.checkpoint.append_prompt_lines(&mut lines);
154 self.append_body_prompt_lines(&mut lines);
155
156 lines.join("\n")
157 }
158
159 pub(crate) fn checkpoint_snapshot(&self) -> String {
160 let mut lines = Vec::new();
161 self.checkpoint.append_prompt_lines(&mut lines);
162 lines.join("\n")
163 }
164
165 pub(crate) fn body_snapshot(&self) -> String {
166 let mut lines = Vec::new();
167 self.append_body_prompt_lines(&mut lines);
168 lines.join("\n")
169 }
170
171 fn append_body_prompt_lines(&self, lines: &mut Vec<String>) {
172 for section in &self.sections {
173 match section {
174 CompiledContextSection::Summary { id, text } => {
175 lines.push(format!("summary:{id}"));
176 lines.push(format!("text:{text}"));
177 }
178 }
179 }
180
181 for memory in &self.memory_projection {
182 lines.push(format!("memory:{}", memory.id));
183 lines.push(format!(
184 "memory-scope:{}",
185 format_memory_scope(memory.scope)
186 ));
187 lines.push(format!("memory-text:{}", memory.text));
188 lines.push(format!(
189 "memory-activation-source-kind:{}",
190 memory.provenance.source_kind().as_str()
191 ));
192 lines.push(format!(
193 "memory-activation-source-label:{}",
194 memory.provenance.source_label()
195 ));
196 lines.push(format!(
197 "memory-activation-query:{}",
198 memory.provenance.canonical_query()
199 ));
200 lines.push(format!(
201 "memory-activation-allowed-scopes:{}",
202 format_memory_scopes(memory.provenance.allowed_scopes())
203 ));
204 for item in &memory.evidence {
205 lines.push(format!("memory-evidence:{}:{}", item.label, item.source));
206 }
207 for reason in &memory.reasons {
208 match reason {
209 CompiledMemoryReason::ScopeAllowed => {
210 lines.push("memory-reason:scope_allowed".to_owned());
211 }
212 CompiledMemoryReason::TriggerMatched(trigger) => {
213 lines.push(format!("memory-reason:trigger:{trigger}"));
214 }
215 CompiledMemoryReason::Ranked { score } => {
216 lines.push(format!(
217 "memory-reason:rank:matches={};priority={};confidence={:.3}",
218 score.trigger_matches(),
219 score.priority(),
220 score.confidence().as_f32()
221 ));
222 }
223 CompiledMemoryReason::ConflictWinner { suppressed } => {
224 lines.push(format!(
225 "memory-reason:conflict_winner:suppressed={}",
226 suppressed
227 .iter()
228 .map(MemoryId::as_str)
229 .collect::<Vec<_>>()
230 .join(",")
231 ));
232 }
233 }
234 }
235 }
236 }
237}
238
239#[derive(Debug, Clone, Default, PartialEq, Eq)]
240struct ContextCheckpointSegment {
241 checkpoint: Option<CompactedCheckpoint>,
242}
243
244const COMPACTED_CHECKPOINT_HEADER: &str = "compacted-checkpoint:";
245const COMPACTED_CHECKPOINT_GUIDANCE: &str = "guidance:This summary is the record of the turns that were removed. Continue from it, and carry it into the next compaction. Re-read workspace files before editing code. A compaction segment named in the summary is the verbatim transcript.";
246const COMPACTED_CHECKPOINT_TEXT_PREFIX: &str = "text:";
247
248pub(crate) fn compacted_checkpoint_wrapper_token_ceiling() -> u64 {
249 let wrapper = format!(
250 "{COMPACTED_CHECKPOINT_HEADER}\n{COMPACTED_CHECKPOINT_GUIDANCE}\n{COMPACTED_CHECKPOINT_TEXT_PREFIX}"
251 );
252 estimate_text_tokens(&wrapper).saturating_add(1)
253}
254
255impl ContextCheckpointSegment {
256 fn new(checkpoint: Option<CompactedCheckpoint>) -> Self {
257 Self { checkpoint }
258 }
259
260 fn append_prompt_lines(&self, lines: &mut Vec<String>) {
261 if let Some(checkpoint) = &self.checkpoint {
262 lines.push(COMPACTED_CHECKPOINT_HEADER.to_owned());
263 lines.push(COMPACTED_CHECKPOINT_GUIDANCE.to_owned());
264 lines.push(format!(
265 "{COMPACTED_CHECKPOINT_TEXT_PREFIX}{}",
266 checkpoint.text()
267 ));
268 }
269 }
270}
271
272#[derive(Debug, Clone, PartialEq, Eq)]
278pub enum CompiledContextSection {
279 Summary {
281 id: String,
283 text: String,
285 },
286}
287
288#[derive(Debug, Clone, PartialEq, Eq)]
289struct CompiledMemory {
290 id: MemoryId,
291 scope: MemoryScope,
292 text: String,
293 evidence: Vec<CompiledMemoryEvidence>,
294 score: MemoryActivationScore,
295 provenance: MemoryActivationProvenance,
296 reasons: Vec<CompiledMemoryReason>,
297}
298
299impl CompiledMemory {
300 fn from_activation(memory: &ActivatedMemory) -> Self {
301 let mut evidence = memory
302 .item()
303 .evidence()
304 .iter()
305 .map(CompiledMemoryEvidence::from_evidence)
306 .collect::<Vec<_>>();
307 evidence.sort();
308 evidence.dedup();
309
310 let mut reasons = memory
311 .reasons()
312 .iter()
313 .map(CompiledMemoryReason::from_reason)
314 .collect::<Vec<_>>();
315 reasons.sort();
316 reasons.dedup();
317
318 Self {
319 id: memory.item().id().clone(),
320 scope: memory.item().scope(),
321 text: memory.item().text().to_owned(),
322 evidence,
323 score: memory.score(),
324 provenance: memory.provenance().clone(),
325 reasons,
326 }
327 }
328}
329
330fn canonical_memory_projection(memories: &[ActivatedMemory]) -> Vec<CompiledMemory> {
331 let mut by_id = BTreeMap::<MemoryId, CompiledMemory>::new();
332
333 for memory in memories.iter().map(CompiledMemory::from_activation) {
334 match by_id.entry(memory.id.clone()) {
335 Entry::Occupied(mut entry) => {
336 if memory.canonical_key() < entry.get().canonical_key() {
337 entry.insert(memory);
338 }
339 }
340 Entry::Vacant(entry) => {
341 entry.insert(memory);
342 }
343 }
344 }
345
346 by_id.into_values().collect()
347}
348
349impl CompiledMemory {
350 fn canonical_key(&self) -> CompiledMemoryCanonicalKey<'_> {
351 (
352 std::cmp::Reverse(self.score),
353 self.scope,
354 self.text.as_str(),
355 self.evidence.as_slice(),
356 &self.provenance,
357 self.reasons.as_slice(),
358 )
359 }
360}
361
362type CompiledMemoryCanonicalKey<'a> = (
363 std::cmp::Reverse<MemoryActivationScore>,
364 MemoryScope,
365 &'a str,
366 &'a [CompiledMemoryEvidence],
367 &'a MemoryActivationProvenance,
368 &'a [CompiledMemoryReason],
369);
370
371#[derive(Debug, Clone, PartialEq, Eq)]
372struct CompiledMemoryEvidence {
373 label: String,
374 source: String,
375}
376
377impl CompiledMemoryEvidence {
378 fn from_evidence(evidence: &MemoryEvidence) -> Self {
379 Self {
380 label: evidence.label().to_owned(),
381 source: evidence.source().to_owned(),
382 }
383 }
384
385 fn sort_key(&self) -> (&str, &str) {
386 (self.source.as_str(), self.label.as_str())
387 }
388}
389
390impl Ord for CompiledMemoryEvidence {
391 fn cmp(&self, other: &Self) -> Ordering {
392 self.sort_key().cmp(&other.sort_key())
393 }
394}
395
396impl PartialOrd for CompiledMemoryEvidence {
397 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
398 Some(self.cmp(other))
399 }
400}
401
402#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
403enum CompiledMemoryReason {
404 ScopeAllowed,
405 TriggerMatched(String),
406 Ranked { score: MemoryActivationScore },
407 ConflictWinner { suppressed: Vec<MemoryId> },
408}
409
410impl CompiledMemoryReason {
411 fn from_reason(reason: &MemoryActivationReason) -> Self {
412 match reason {
413 MemoryActivationReason::ScopeAllowed => Self::ScopeAllowed,
414 MemoryActivationReason::TriggerMatched(trigger) => {
415 Self::TriggerMatched(canonicalize_memory_reason_text(trigger))
416 }
417 MemoryActivationReason::Ranked { score } => Self::Ranked { score: *score },
418 MemoryActivationReason::ConflictWinner { suppressed } => {
419 let mut suppressed = suppressed.clone();
420 suppressed.sort();
421 suppressed.dedup();
422 Self::ConflictWinner { suppressed }
423 }
424 }
425 }
426}
427
428impl CompiledContextSection {
429 fn sort_key(&self) -> (&str, &str) {
430 match self {
431 Self::Summary { id, .. } => ("summary", id.as_str()),
432 }
433 }
434}