Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions crates/ox-core/src/agent/compaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use super::tools::inject_always_active_skills;
use super::{Agent, AgentConfig, AgentEvent, RunContext, SystemPromptRefresher};
use crate::compaction::{
CompactRequest, CompactionError, CompactionOutcome, CompactionTrigger,
MAX_PRESERVED_DEFERRED_TOOL_SCHEMA_CHARS, compact_messages, prune_deferred_tools,
MAX_PRESERVED_DEFERRED_TOOL_SCHEMA_CHARS, attach_archive_pointer, compact_messages,
prune_deferred_tools,
};
use crate::hooks::{HookInput, HookOutcome, HookRunner};
use crate::message::Message;
Expand Down Expand Up @@ -52,10 +53,10 @@ impl Agent {
focus,
hook_guidance: hook_guidance.as_deref(),
};
let (next_messages, outcome) = compact_messages(&req, &self.history).await?;
let (mut next_messages, mut outcome) = compact_messages(&req, &self.history).await?;

if let Some((store, session_id)) = &self.runtime.session {
persist_compaction(store, session_id, &outcome)?;
persist_compaction(store, session_id, &mut outcome, &mut next_messages)?;
}

self.history = next_messages;
Expand Down Expand Up @@ -102,9 +103,10 @@ pub(super) async fn maybe_auto_compact(
};

match compact_messages(&req, messages).await {
Ok((next_messages, outcome)) => {
Ok((mut next_messages, mut outcome)) => {
if let Some((store, session_id)) = &ctx.runtime.session
&& let Err(err) = persist_compaction(store, session_id, &outcome)
&& let Err(err) =
persist_compaction(store, session_id, &mut outcome, &mut next_messages)
{
tracing::warn!(error = %err, "failed to persist auto-compaction record");
}
Expand Down Expand Up @@ -172,7 +174,8 @@ async fn run_pre_compact_hooks_inner(
fn persist_compaction(
store: &Arc<Mutex<SessionStore>>,
session_id: &str,
outcome: &CompactionOutcome,
outcome: &mut CompactionOutcome,
next_messages: &mut [Message],
) -> Result<(), SessionError> {
let guard = crate::lock_unpoisoned(store);
let stored = guard.load_messages(session_id)?;
Expand All @@ -199,11 +202,12 @@ fn persist_compaction(
msg.seq
};

_ = guard.record_compaction(
session_id,
up_to_seq,
&outcome.summary,
outcome.trigger.as_str(),
)?;
let start_seq = stored.first().map_or(0, |m| m.seq);
let summary = attach_archive_pointer(&outcome.summary, session_id, start_seq, up_to_seq);
_ = guard.record_compaction(session_id, up_to_seq, &summary, outcome.trigger.as_str())?;
outcome.summary.clone_from(&summary);
if let Some(first) = next_messages.first_mut() {
*first = Message::user(summary);
}
Ok(())
}
14 changes: 13 additions & 1 deletion crates/ox-core/src/agent/tests/compaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use tempfile::{TempDir, tempdir};
use super::super::{Agent, AgentConfig, AgentEvent};
use super::{empty_agent, seeded_session_store};
use crate::client::{ClientError, ResponseEvent, StopReason, Usage, Wire};
use crate::compaction::{CompactionTrigger, SUMMARY_OPEN_TAG};
use crate::compaction::{CompactionTrigger, SUMMARY_OPEN_TAG, parse_compaction_summary};
use crate::message::Message;
use crate::plugin::{PluginManager, PluginManifest, RpcError};
use crate::session::SessionStore;
Expand Down Expand Up @@ -72,6 +72,18 @@ async fn manual_compact_persists_refreshes_system_and_falls_back_from_failing_pl
.expect("persisted compaction");
assert_eq!(latest.up_to_seq, 1);
assert_eq!(latest.trigger, "manual");
let parsed = parse_compaction_summary(&latest.summary).expect("parse persisted summary");
assert_eq!(parsed.summary, "## Goal\nFallback summary");
assert_eq!(
parsed.archived_session_id.as_deref(),
Some("session-compact")
);
assert_eq!(parsed.archived_seq_range, Some((0, 1)));
assert_eq!(
parse_compaction_summary(&outcome.summary),
Some(parsed),
"in-memory outcome summary should match persisted summary"
);
}

#[tokio::test]
Expand Down
149 changes: 149 additions & 0 deletions crates/ox-core/src/compaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ pub const MAX_COMPACTION_TOOL_OUTPUTS_CHARS: usize = 64_000;
const MODIFIED_FILES_TAG: &str = "modified-files";
const READ_FILES_TAG: &str = "read-files";
const ACTIVE_SKILLS_TAG: &str = "active-skills";
const ARCHIVED_TRANSCRIPT_PREFIX: &str = "<archived-transcript";

const MIN_PRESERVED_SKILL_CHARS: usize = 64;
const TRUNCATION_MARKER: &str = "\n[truncated]";
Expand Down Expand Up @@ -120,6 +121,18 @@ pub struct CompactionOutcome {
pub compacted_prefix_len: usize,
}

/// Parsed representation of a `<compaction-summary>` message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompactionSummaryView {
/// Inner summary body with any `<archived-transcript ... />` pointer stripped.
pub summary: String,
/// Session identifier referenced by an `<archived-transcript>` pointer, if present.
pub archived_session_id: Option<String>,
/// Inclusive `(start_seq, end_seq)` sequence range referenced by an `<archived-transcript>`
/// pointer, if present.
pub archived_seq_range: Option<(i64, i64)>,
}

/// Estimates the approximate token count of `message` using `chars / 4` plus a fixed allowance per
/// attachment.
pub fn estimate_message_tokens(message: &Message) -> u64 {
Expand Down Expand Up @@ -194,6 +207,36 @@ pub fn extract_prior_summary(messages: &[Message]) -> Option<&str> {
None
}

/// Parses a `<compaction-summary>` message into its summary body and optional archival pointer.
///
/// Returns `None` when `text` does not contain a `<compaction-summary>...</compaction-summary>`
/// block.
pub fn parse_compaction_summary(text: &str) -> Option<CompactionSummaryView> {
let inner = extract_tag_inner(text, SUMMARY_OPEN_TAG, SUMMARY_CLOSE_TAG)?;
let Some(pointer) = extract_archived_transcript_pointer(inner) else {
return Some(CompactionSummaryView {
summary: inner.to_owned(),
archived_session_id: None,
archived_seq_range: None,
});
};

let before = inner[..pointer.start].trim_end();
let after = inner[pointer.end..].trim_start();
let summary = match (before.is_empty(), after.is_empty()) {
(true, true) => String::new(),
(false, true) => before.to_owned(),
(true, false) => after.to_owned(),
(false, false) => format!("{before}\n\n{after}"),
};

Some(CompactionSummaryView {
summary,
archived_session_id: pointer.session_id,
archived_seq_range: pointer.seq_range,
})
}

/// Resolves the compaction system prompt with precedence:
/// `<cwd>/.ox/prompts/compact.md` > `config.prompt_file` > `config.prompt` > built-in template.
///
Expand Down Expand Up @@ -694,6 +737,38 @@ fn wrap_summary(body: &str, files: &ExtractedFiles, skills_block: Option<&str>)
}
}

/// Inserts an `<archived-transcript ... />` pointer inside a wrapped `<compaction-summary>` block.
pub(crate) fn attach_archive_pointer(
summary: &str,
session_id: &str,
start_seq: i64,
end_seq: i64,
) -> String {
let escaped_id = escape_xml_attr(session_id);
let pointer = format!(
r#"<archived-transcript session="{escaped_id}" seq="{start_seq}..={end_seq}" command="ox sessions show {escaped_id} --full" />"#
);
let Some(prefix) = summary.trim_end().strip_suffix(SUMMARY_CLOSE_TAG) else {
return format!("{summary}\n\n{pointer}");
};
let prefix = prefix.trim_end();
format!("{prefix}\n\n{pointer}\n{SUMMARY_CLOSE_TAG}")
}

fn escape_xml_attr(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for ch in value.chars() {
match ch {
'&' => out.push_str("&amp;"),
'"' => out.push_str("&quot;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
other => out.push(other),
}
}
out
}

fn format_xml_block(tag: &str, body: &str) -> String {
formatdoc! {"
<{tag}>
Expand All @@ -714,6 +789,80 @@ fn extract_tag_inner<'a>(text: &'a str, open: &str, close: &str) -> Option<&'a s
Some(text[start..end].trim())
}

struct ArchivedTranscriptPointer {
start: usize,
end: usize,
session_id: Option<String>,
seq_range: Option<(i64, i64)>,
}

fn extract_archived_transcript_pointer(text: &str) -> Option<ArchivedTranscriptPointer> {
let start = text.rfind(ARCHIVED_TRANSCRIPT_PREFIX)?;
let rest = &text[start..];
let close_offset = rest.find("/>")?;
let end = start + close_offset + 2;
let tag = &text[start..end];

let session_id = extract_xml_attr(tag, "session");
let seq_range = extract_xml_attr(tag, "seq").and_then(|raw| parse_seq_range(&raw));
Some(ArchivedTranscriptPointer {
start,
end,
session_id,
seq_range,
})
}

fn extract_xml_attr(tag: &str, name: &str) -> Option<String> {
let marker = format!(r#"{name}=""#);
let start = tag.find(&marker)? + marker.len();
let end = tag[start..].find('"')? + start;
let value = &tag[start..end];
if value.is_empty() {
None
} else {
Some(unescape_xml_attr(value))
}
}

fn unescape_xml_attr(value: &str) -> String {
let mut out = String::with_capacity(value.len());
let mut rest = value;
while let Some(pos) = rest.find('&') {
out.push_str(&rest[..pos]);
let after = &rest[pos..];
if let Some(tail) = after.strip_prefix("&amp;") {
out.push('&');
rest = tail;
} else if let Some(tail) = after.strip_prefix("&quot;") {
out.push('"');
rest = tail;
} else if let Some(tail) = after.strip_prefix("&lt;") {
out.push('<');
rest = tail;
} else if let Some(tail) = after.strip_prefix("&gt;") {
out.push('>');
rest = tail;
} else {
out.push('&');
rest = &after[1..];
}
}
out.push_str(rest);
out
}

fn parse_seq_range(raw: &str) -> Option<(i64, i64)> {
let (start, end) = raw.split_once("..=").or_else(|| raw.split_once(".."))?;
let start = start.trim().parse::<i64>().ok()?;
let end = end.trim().parse::<i64>().ok()?;
if start <= end {
Some((start, end))
} else {
None
}
}

fn extract_path_arg(arguments: &Value) -> Option<&str> {
crate::agent::extract_file_path(arguments)
}
Expand Down
72 changes: 68 additions & 4 deletions crates/ox-core/src/compaction/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ use serde_json::{Value, json};
use tempfile::tempdir;

use super::{
ATTACHMENT_TOKEN_ESTIMATE, CompactRequest, CompactionError, CompactionTrigger,
MAX_COMPACTION_TOOL_OUTPUTS_CHARS, MAX_PRESERVED_SKILLS_CHARS, compact_messages,
default_compaction_prompt, estimate_message_tokens, extract_active_skills_block, extract_files,
find_cut_point, format_active_skills_block_with_budget, format_transcript,
ATTACHMENT_TOKEN_ESTIMATE, CompactRequest, CompactionError, CompactionSummaryView,
CompactionTrigger, MAX_COMPACTION_TOOL_OUTPUTS_CHARS, MAX_PRESERVED_SKILLS_CHARS,
attach_archive_pointer, compact_messages, default_compaction_prompt, estimate_message_tokens,
extract_active_skills_block, extract_files, find_cut_point,
format_active_skills_block_with_budget, format_transcript, parse_compaction_summary,
prune_deferred_tools, resolve_compaction_prompt, resolve_compaction_prompt_with_model,
};
use crate::client::{ResponseEvent, StopReason};
Expand Down Expand Up @@ -168,6 +169,69 @@ fn find_cut_point_snaps_to_user_turn_and_never_splits_tool_pairs() {
assert_eq!(find_cut_point(&messages, 200), None);
}

#[test]
fn parse_compaction_summary_handles_plain_archived_and_non_summary_text() {
let plain = indoc! {"
<compaction-summary>
## Goal
Ship compaction epochs.
</compaction-summary>"
};
assert_eq!(
parse_compaction_summary(plain),
Some(CompactionSummaryView {
summary: "## Goal\nShip compaction epochs.".to_owned(),
archived_session_id: None,
archived_seq_range: None,
})
);

let with_pointer = attach_archive_pointer(plain, "session-42", 0, 7);
assert!(with_pointer.contains("ox sessions show session-42 --full"));
assert_eq!(
parse_compaction_summary(&with_pointer),
Some(CompactionSummaryView {
summary: "## Goal\nShip compaction epochs.".to_owned(),
archived_session_id: Some("session-42".to_owned()),
archived_seq_range: Some((0, 7)),
})
);

let special_id = r#"s&"1"<2>"#;
let escaped = attach_archive_pointer(&format!("{plain}\n"), special_id, 0, 3);
assert!(escaped.contains(r#"session="s&amp;&quot;1&quot;&lt;2&gt;""#));
assert_eq!(
parse_compaction_summary(&escaped),
Some(CompactionSummaryView {
summary: "## Goal\nShip compaction epochs.".to_owned(),
archived_session_id: Some(special_id.to_owned()),
archived_seq_range: Some((0, 3)),
})
);

let dot_dot = indoc! {r#"
<compaction-summary>
Summary body

<archived-transcript session="session-7" seq="1..4" command="ox sessions show session-7 --full" />
</compaction-summary>"#
};
assert_eq!(
parse_compaction_summary(dot_dot),
Some(CompactionSummaryView {
summary: "Summary body".to_owned(),
archived_session_id: Some("session-7".to_owned()),
archived_seq_range: Some((1, 4)),
})
);

assert_eq!(parse_compaction_summary("ordinary user message"), None);
assert_eq!(
parse_compaction_summary("<compaction-summary>unclosed"),
None
);
}

#[test]
fn format_transcript_fairly_budgets_tool_outputs() {
let small_output = "small tool output";
Expand Down
Loading
Loading