Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

configure automatic compaction percentage (#3577)

kta498cbd49321
diff --git a/.changes/configurable-autocompact.md b/.changes/configurable-autocompact.md
new file mode 100644
index 0000000000..0cea30b7ed
--- /dev/null
+++ b/.changes/configurable-autocompact.md
@@ -0,0 +1 @@
+Added a configurable auto-compaction percentage with five-point settings steps, retention-aware triggering, and preserved model output headroom.
diff --git a/README.md b/README.md
index 112c8cc9fa..a76673daff 100644
--- a/README.md
+++ b/README.md
@@ -140,3 +140,30 @@ If you use this codebase in your research, please cite Prime Agent:
```
Available at [https://arxiv.org/abs/2608.23552](https://arxiv.org/abs/2608.23552).
+
+### Automatic compaction settings
+
+`/settings` exposes the global automatic compaction percentage in five-point steps,
+with a 95% default. A saved off-grid percentage stays selectable. The effective
+trigger also reserves room for retained history and summaries; the model's input
+and requested-output ceiling always takes priority. Manual compaction budgets are
+unchanged. The underlying `compaction.thresholdPercent` setting accepts 1–100,
+including fractional values; project settings can override the global setting.
+
+For per-model early compaction, use the existing provider-scoped
+`modelOverrides.<id>.contextWindow` option in `models.json`, for example:
+
+```json
+{
+ "providers": {
+ "prime-inference": {
+ "modelOverrides": {
+ "your-model-id": { "contextWindow": 524288 }
+ }
+ }
+ }
+}
+```
+
+Use the actual model ID for your provider. This sets that model's effective context
+window; it does not change every model's global compaction percentage.
diff --git a/crates/pa-cli/src/client_settings.rs b/crates/pa-cli/src/client_settings.rs
index c875c08cf1..5aeeaaeded 100644
--- a/crates/pa-cli/src/client_settings.rs
+++ b/crates/pa-cli/src/client_settings.rs
@@ -49,6 +49,30 @@ macro_rules! str_setting {
}
impl ClientSettings for CliClientSettings {
+ fn compaction_threshold_percent(&self) -> f64 {
+ self.manager().get_compaction_threshold_percent()
+ }
+
+ fn set_compaction_threshold_percent(&self, percent: f64) -> Result<()> {
+ self.manager().set_compaction_threshold_percent(percent)?;
+ let settings = self.clone();
+ if let Ok(runtime) = tokio::runtime::Handle::try_current() {
+ runtime.spawn(async move {
+ let manager = settings.manager();
+ if crate::mode::telemetry_disabled(&manager) {
+ return;
+ }
+ let client =
+ pa_core::session_engine::telemetry::build_client(&manager, &settings.agent_dir);
+ let mut properties = pa_telemetry::base_properties("interactive");
+ properties.set("threshold_percent", serde_json::json!(percent));
+ client.track("autocompact threshold changed", properties);
+ let _ = client.shutdown().await;
+ });
+ }
+ Ok(())
+ }
+
fn theme(&self) -> Option<String> {
self.manager().get_theme().map(str::to_string)
}
diff --git a/crates/pa-core/src/session_engine/compaction.rs b/crates/pa-core/src/session_engine/compaction.rs
index 01643f09e2..afff07ced4 100644
--- a/crates/pa-core/src/session_engine/compaction.rs
+++ b/crates/pa-core/src/session_engine/compaction.rs
@@ -5,12 +5,17 @@
use pa_types::session::{AgentMessage, FileEntry};
use std::fmt::Write as _;
+#[cfg(test)]
+#[path = "compaction_threshold_tests.rs"]
+mod threshold_tests;
+
pub const DEFAULT_RESERVE_TOKENS: u64 = 16_384;
pub const DEFAULT_KEEP_RECENT_TOKENS: u64 = 20_000;
/// The percentage of the context window past which a threshold compaction
/// always fires (guards estimate drift on large windows).
pub const COMPACT_THRESHOLD_RATIO: f64 = 0.95;
+pub const DEFAULT_THRESHOLD_PERCENT: f64 = COMPACT_THRESHOLD_RATIO * 100.0;
/// The smallest headroom kept under the combined input+output ceiling (the
/// chars/4 estimate error); `reserve_tokens` raises it when larger.
@@ -19,6 +24,8 @@ pub const COMBINED_LIMIT_HEADROOM_FLOOR: u64 = 4_096;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CompactionSettings {
pub enabled: bool,
+ /// Requested percentage ceiling; output and reserve headroom can trigger earlier.
+ pub threshold_percent: f64,
/// Headroom under the combined input+output ceiling (a floor of
/// [`COMBINED_LIMIT_HEADROOM_FLOOR`]): combined-limit providers reject
/// `input + requested output > contextWindow`.
@@ -30,6 +37,7 @@ impl Default for CompactionSettings {
fn default() -> Self {
Self {
enabled: true,
+ threshold_percent: DEFAULT_THRESHOLD_PERCENT,
reserve_tokens: DEFAULT_RESERVE_TOKENS,
keep_recent_tokens: DEFAULT_KEEP_RECENT_TOKENS,
}
@@ -141,8 +149,8 @@ fn div4(chars: u64) -> u64 {
chars.div_ceil(4)
}
-/// The effective compaction threshold: the earlier of two ceilings.
-/// PERCENTAGE: `context_window * COMPACT_THRESHOLD_RATIO` (estimate drift on
+/// The effective compaction threshold: a retention-floored percentage capped by model safety.
+/// PERCENTAGE: `context_window * threshold_percent / 100` (estimate drift on
/// large windows). COMBINED-LIMIT: `context_window - max_output_tokens -
/// max(reserve_tokens, COMBINED_LIMIT_HEADROOM_FLOOR)`: the output budget
/// must still fit. TS checks only `contextWindow - reserveTokens`; reserving
@@ -154,7 +162,20 @@ pub fn compaction_threshold(
max_output_tokens: u64,
settings: &CompactionSettings,
) -> u64 {
- let percentage = (context_window as f64 * COMPACT_THRESHOLD_RATIO) as u64;
+ let percent = if pa_types::compaction::is_valid_threshold_percent(settings.threshold_percent) {
+ settings.threshold_percent
+ } else {
+ DEFAULT_THRESHOLD_PERCENT
+ };
+ let requested = (context_window as f64 * (percent / 100.0)) as u64;
+ // Retained history and both summary passes must fit below the trigger,
+ // otherwise a low percentage re-summarizes the same retained context on
+ // every tool turn. Two reserves cover both summary completion budgets.
+ let retention_floor = settings
+ .keep_recent_tokens
+ .saturating_add(settings.reserve_tokens.saturating_mul(2))
+ .saturating_add(1);
+ let percentage = requested.max(retention_floor);
let headroom = settings.reserve_tokens.max(COMBINED_LIMIT_HEADROOM_FLOOR);
let combined = context_window
.saturating_sub(max_output_tokens)
@@ -598,6 +619,7 @@ mod tests {
// 126_010 tokens on a 128k window with a 127_500 reserve leaves
// a 500-token combined ceiling — the crossing fires.
let settings = CompactionSettings {
+ threshold_percent: 95.0,
enabled: true,
reserve_tokens: 127_500,
keep_recent_tokens: 10,
@@ -615,6 +637,7 @@ mod tests {
];
assert!(!threshold_compaction_due(&messages, 128_000, 0, &settings));
let disabled = CompactionSettings {
+ threshold_percent: 95.0,
enabled: false,
reserve_tokens: 127_500,
keep_recent_tokens: 10,
@@ -682,6 +705,7 @@ mod tests {
// A tiny reserve still keeps the 4_096 estimate-error floor:
// 131_072 - 32_768 - 4_096 = 94_208 < the 95% ceiling.
let settings = CompactionSettings {
+ threshold_percent: 95.0,
enabled: true,
reserve_tokens: 1,
keep_recent_tokens: 10,
@@ -704,6 +728,7 @@ mod tests {
#[test]
fn stale_pre_compaction_usage_never_retriggers() {
let settings = CompactionSettings {
+ threshold_percent: 95.0,
enabled: true,
reserve_tokens: 127_500,
keep_recent_tokens: 10,
diff --git a/crates/pa-core/src/session_engine/compaction_threshold_tests.rs b/crates/pa-core/src/session_engine/compaction_threshold_tests.rs
new file mode 100644
index 0000000000..6a82503c63
--- /dev/null
+++ b/crates/pa-core/src/session_engine/compaction_threshold_tests.rs
@@ -0,0 +1,130 @@
+use super::*;
+
+#[test]
+fn default_percentage_preserves_the_current_threshold_and_strict_boundary() {
+ let settings = CompactionSettings::default();
+ for (window, output, expected) in [
+ (1_048_576, 32_000, 996_147),
+ (131_072, 32_768, 81_920),
+ (128_000, 0, 111_616),
+ (0, 0, 0),
+ ] {
+ assert_eq!(compaction_threshold(window, output, &settings), expected);
+ assert!(!should_compact(expected, window, output, &settings));
+ assert_eq!(
+ should_compact(expected + 1, window, output, &settings),
+ expected > 0
+ );
+ }
+}
+
+#[test]
+fn custom_percentages_obey_both_ceilings_as_model_limits_change() {
+ for (percent, expected_by_model) in [
+ (1.0, [52_769, 52_769, 17_152]),
+ (50.0, [524_288, 65_536, 17_152]),
+ (62.5, [655_360, 81_920, 17_152]),
+ (80.0, [838_860, 81_920, 17_152]),
+ (95.0, [996_147, 81_920, 17_152]),
+ (100.0, [1_000_192, 81_920, 17_152]),
+ ] {
+ let settings = CompactionSettings {
+ threshold_percent: percent,
+ ..Default::default()
+ };
+ for ((window, output), expected) in
+ [(1_048_576, 32_000), (131_072, 32_768), (65_536, 32_000)]
+ .into_iter()
+ .zip(expected_by_model)
+ {
+ assert_eq!(compaction_threshold(window, output, &settings), expected);
+ assert!(!should_compact(expected, window, output, &settings));
+ assert!(should_compact(expected + 1, window, output, &settings));
+ }
+ }
+}
+
+#[test]
+fn invalid_runtime_percentages_fall_back_without_losing_headroom() {
+ for percent in [
+ 0.0,
+ -1.0,
+ 100.01,
+ f64::NAN,
+ f64::INFINITY,
+ f64::NEG_INFINITY,
+ ] {
+ let settings = CompactionSettings {
+ threshold_percent: percent,
+ ..Default::default()
+ };
+ assert_eq!(compaction_threshold(1_048_576, 32_000, &settings), 996_147);
+ assert_eq!(compaction_threshold(131_072, 32_768, &settings), 81_920);
+ }
+ let settings = CompactionSettings {
+ threshold_percent: 100.0,
+ reserve_tokens: 1,
+ ..Default::default()
+ };
+ assert_eq!(compaction_threshold(131_072, 32_768, &settings), 94_208);
+ assert_eq!(compaction_threshold(4_000, 32_000, &settings), 0);
+}
+
+#[tokio::test]
+async fn saved_percentage_applies_to_existing_sessions_without_changing_manual_budgets() {
+ let dir = tempfile::tempdir().unwrap();
+ let agent_dir = dir.path().join("agent");
+ let agent = std::sync::Arc::new(pa_agent::agent::Agent::new(
+ pa_agent::agent::AgentOptions::default(),
+ ));
+ let mut session = super::super::AgentSession::new(
+ agent,
+ crate::session::manager::SessionManager::in_memory(dir.path()),
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+ session.set_compaction_settings(CompactionSettings {
+ reserve_tokens: 12_345,
+ keep_recent_tokens: 567,
+ ..Default::default()
+ });
+ session.set_auxiliary_model_context(super::super::auxiliary_model::AuxiliaryModelContext {
+ cwd: dir.path().to_path_buf(),
+ agent_dir: agent_dir.clone(),
+ });
+ let mut settings = crate::settings::SettingsManager::create(dir.path(), &agent_dir);
+ assert_eq!(session.compaction_settings().threshold_percent, 95.0);
+ settings.set_compaction_threshold_percent(80.5).unwrap();
+ assert_eq!(
+ session.compaction_settings(),
+ CompactionSettings {
+ threshold_percent: 80.5,
+ reserve_tokens: 12_345,
+ keep_recent_tokens: 567,
+ ..Default::default()
+ }
+ );
+ session.set_auto_compaction_enabled(false);
+ assert!(!should_compact(
+ 1_000_000,
+ 1_048_576,
+ 32_000,
+ &session.compaction_settings()
+ ));
+}
+
+#[test]
+fn low_percentages_leave_room_for_retained_history_and_both_summaries() {
+ for percent in [1.0, 5.0, 10.0] {
+ let settings = CompactionSettings {
+ threshold_percent: percent,
+ ..Default::default()
+ };
+ assert_eq!(compaction_threshold(128_000, 16_384, &settings), 52_769);
+ assert!(!should_compact(52_769, 128_000, 16_384, &settings));
+ assert!(should_compact(52_770, 128_000, 16_384, &settings));
+ // The hard combined model ceiling wins even if retention cannot fit.
+ assert_eq!(compaction_threshold(65_536, 32_000, &settings), 17_152);
+ }
+}
diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rs
index c98f98090a..85963eb3e7 100644
--- a/crates/pa-core/src/session_engine/engine.rs
+++ b/crates/pa-core/src/session_engine/engine.rs
@@ -247,6 +247,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S
// Captured before `settings` moves into the resource loader: the
// compaction budget and the auto-refine gates.
let compaction_settings = settings.settings().compaction.clone().unwrap_or_default();
+ let compaction_threshold_percent = settings.get_compaction_threshold_percent();
let auto_refine_gates =
super::refine::AutoRefineGates::from_settings(settings.settings().auto_refine.as_ref());
// Request timing: the settings half of the flag is read once here
@@ -697,6 +698,7 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S
// settings (TS `getCompactionSettings`): `/compact` matches the
// `compact.*` turn-boundary tool's `keepRecentTokens`/`reserveTokens`.
session.set_compaction_settings(crate::session_engine::compaction::CompactionSettings {
+ threshold_percent: compaction_threshold_percent,
enabled: compaction_settings.enabled.unwrap_or(true),
reserve_tokens: compaction_settings
.reserve_tokens
diff --git a/crates/pa-core/src/session_engine/wiring.rs b/crates/pa-core/src/session_engine/wiring.rs
index b9b4de55fc..167e1f5e62 100644
--- a/crates/pa-core/src/session_engine/wiring.rs
+++ b/crates/pa-core/src/session_engine/wiring.rs
@@ -167,10 +167,19 @@ impl AgentSession {
/// The resolved compaction settings: the in-run continuation consult reads the threshold
/// headroom without owning the session (a compaction in flight owns it across its model turn).
pub fn compaction_settings(&self) -> compaction::CompactionSettings {
- *self
+ let mut resolved = *self
.compaction
.read()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ // Read only the percentage at decision boundaries, off the paint path.
+ // Like auxiliary-model routing, another client's settings save applies
+ // to an already-running session without changing manual summary budgets.
+ if let Some(context) = &self.auxiliary_model {
+ resolved.threshold_percent =
+ crate::settings::SettingsManager::create(&context.cwd, &context.agent_dir)
+ .get_compaction_threshold_percent();
+ }
+ resolved
}
/// Install the session's semantic-edge recorder (the engine build's
diff --git a/crates/pa-core/src/settings/interactive_settings.rs b/crates/pa-core/src/settings/interactive_settings.rs
index e793e72e10..a95f17ca42 100644
--- a/crates/pa-core/src/settings/interactive_settings.rs
+++ b/crates/pa-core/src/settings/interactive_settings.rs
@@ -7,6 +7,34 @@ use anyhow::{anyhow, Result};
use super::manager::SettingsManager;
impl SettingsManager {
+ /// The percentage ceiling for automatic compaction (default 95%).
+ #[must_use]
+ pub fn get_compaction_threshold_percent(&self) -> f64 {
+ self.settings()
+ .compaction
+ .as_ref()
+ .and_then(|settings| settings.threshold_percent)
+ .filter(|percent| pa_types::compaction::is_valid_threshold_percent(*percent))
+ .unwrap_or(crate::session_engine::compaction::DEFAULT_THRESHOLD_PERCENT)
+ }
+
+ /// Persist the requested percentage without changing reserve or summary budgets.
+ ///
+ /// # Errors
+ /// Returns an error for values outside 1–100%, non-finite values, or a failed save.
+ pub fn set_compaction_threshold_percent(&mut self, percent: f64) -> Result<()> {
+ if !pa_types::compaction::is_valid_threshold_percent(percent) {
+ return Err(anyhow!(
+ "Auto-compact threshold must be a number from 1 to 100 percent"
+ ));
+ }
+ self.global_mut()
+ .compaction
+ .get_or_insert_with(Default::default)
+ .threshold_percent = Some(percent);
+ self.save_global_scope(&["compaction.thresholdPercent"])
+ }
+
/// # Errors
///
/// Returns an error when the global settings scope cannot be saved.
diff --git a/crates/pa-core/src/settings/persistence_tests.rs b/crates/pa-core/src/settings/persistence_tests.rs
index 0bc72807fb..725f8e4dbf 100644
--- a/crates/pa-core/src/settings/persistence_tests.rs
+++ b/crates/pa-core/src/settings/persistence_tests.rs
@@ -130,3 +130,93 @@ fn resource_save_survives_an_unrelated_later_save() {
json!({"packages":["second"],"theme":"dark"})
);
}
+
+#[test]
+fn compaction_percentage_preserves_siblings_and_survives_reload() {
+ let (storage, mut manager) =
+ fixture(r#"{"compaction":{"enabled":false,"reserveTokens":1234,"future":"keep"}}"#);
+ assert_eq!(manager.get_compaction_threshold_percent(), 95.0);
+ for percent in [1.0, 62.5, 95.0, 100.0] {
+ manager.set_compaction_threshold_percent(percent).unwrap();
+ manager.reload().unwrap();
+ assert_eq!(manager.get_compaction_threshold_percent(), percent);
+ assert_eq!(
+ document(storage.as_ref()),
+ json!({"compaction":{
+ "enabled":false,"reserveTokens":1234,"future":"keep","thresholdPercent":percent
+ }})
+ );
+ }
+}
+
+#[test]
+fn invalid_compaction_percentage_never_mutates_or_saves() {
+ let (storage, mut manager) = fixture(r#"{"compaction":{"thresholdPercent":80.0}}"#);
+ for percent in [
+ 0.0,
+ -1.0,
+ 100.01,
+ f64::NAN,
+ f64::INFINITY,
+ f64::NEG_INFINITY,
+ ] {
+ assert!(manager.set_compaction_threshold_percent(percent).is_err());
+ assert_eq!(manager.get_compaction_threshold_percent(), 80.0);
+ assert_eq!(
+ document(storage.as_ref()),
+ json!({"compaction":{"thresholdPercent":80.0}})
+ );
+ }
+}
+
+#[test]
+fn invalid_loaded_percentage_keeps_other_compaction_settings() {
+ for invalid in [
+ json!(null),
+ json!("80"),
+ json!(false),
+ json!(-1),
+ json!(0),
+ json!(101),
+ json!({}),
+ json!([]),
+ ] {
+ let settings = super::load::from_value_lenient(&json!({"compaction":{
+ "enabled":false,"reserveTokens":1234,"thresholdPercent":invalid
+ }}));
+ let manager = SettingsManager::in_memory(&settings);
+ assert_eq!(manager.get_compaction_threshold_percent(), 95.0);
+ assert!(!manager.get_compaction_enabled());
+ assert_eq!(
+ manager
+ .settings()
+ .compaction
+ .as_ref()
+ .unwrap()
+ .reserve_tokens,
+ Some(1234)
+ );
+ }
+}
+
+#[test]
+fn project_percentage_overrides_global_and_stale_writes_preserve_external_settings() {
+ let (storage, mut first) = fixture(r#"{"compaction":{"thresholdPercent":80.0}}"#);
+ let mut second = SettingsManager::from_storage(storage.clone());
+ second.set_compaction_enabled(false).unwrap();
+ first.set_compaction_threshold_percent(70.0).unwrap();
+ assert_eq!(
+ document(storage.as_ref()),
+ json!({"compaction":{"enabled":false,"thresholdPercent":70.0}})
+ );
+ storage
+ .with_lock(SettingsScope::Project, &mut |_| {
+ Some(r#"{"compaction":{"thresholdPercent":60.5}}"#.into())
+ })
+ .unwrap();
+ first.reload().unwrap();
+ assert_eq!(first.get_compaction_threshold_percent(), 60.5);
+ first.set_compaction_threshold_percent(90.0).unwrap();
+ first.reload().unwrap();
+ assert_eq!(first.get_compaction_threshold_percent(), 60.5);
+}
diff --git a/crates/pa-core/src/settings/types.rs b/crates/pa-core/src/settings/types.rs
index 04bf062bd8..95c4a22175 100644
--- a/crates/pa-core/src/settings/types.rs
+++ b/crates/pa-core/src/settings/types.rs
@@ -81,6 +81,15 @@ pub enum TransportSetting {
WebSocketCached,
}
+fn deserialize_threshold_percent<'de, D: serde::Deserializer<'de>>(
+ deserializer: D,
+) -> Result<Option<f64>, D::Error> {
+ let value = serde_json::Value::deserialize(deserializer)?;
+ Ok(value
+ .as_f64()
+ .filter(|percent| pa_types::compaction::is_valid_threshold_percent(*percent)))
+}
+
/// `number | "unlimited"` autonomous limit.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
@@ -93,6 +102,9 @@ pub enum AutonomousLimitSetting {
#[serde(rename_all = "camelCase")]
pub struct CompactionSettings {
pub enabled: Option<bool>,
+ /// Percentage ceiling for automatic compaction; invalid values behave as unset.
+ #[serde(default, deserialize_with = "deserialize_threshold_percent")]
+ pub threshold_percent: Option<f64>,
pub reserve_tokens: Option<u64>,
pub keep_recent_tokens: Option<u64>,
pub agent_callable: Option<bool>,
diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rs
index 7c75a2acbd..a320932e1b 100644
--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs
+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs
@@ -260,9 +260,9 @@ impl AgentSessionEngine {
return Ok(());
}
}
- let built = self.build_session(model).await?;
+ let built = Arc::new(self.build_session(model).await?);
self.adopt_built_session(&built).await?;
- self.session.lock().await.replace(Arc::new(built));
+ self.session.lock().await.replace(built);
Ok(())
}
@@ -337,7 +337,7 @@ impl AgentSessionEngine {
}
}
- async fn adopt_built_session(&self, built: &CoreSessionEngine) -> anyhow::Result<()> {
+ async fn adopt_built_session(&self, built: &Arc<CoreSessionEngine>) -> anyhow::Result<()> {
self.mirror_goal_runtime(built).await;
*self
.progress_notes
@@ -361,7 +361,7 @@ impl AgentSessionEngine {
Some(crate::autonomous_continuation::AutonomousBoundaryMirror {
turn_boundary: std::sync::Arc::clone(&built.turn_boundary),
agent: std::sync::Arc::clone(built.session.agent()),
- compaction: built.session.compaction_settings(),
+ session: Arc::downgrade(built),
});
// The background-bash liveness probe: a deadlock-free read over the
// build's provisioner.
diff --git a/crates/pa-daemon/src/agent_engine/tests/compaction.rs b/crates/pa-daemon/src/agent_engine/tests/compaction.rs
index 2ea7cd001e..a4db41d9b0 100644
--- a/crates/pa-daemon/src/agent_engine/tests/compaction.rs
+++ b/crates/pa-daemon/src/agent_engine/tests/compaction.rs
@@ -1214,3 +1214,97 @@ fn a_not_due_recheck_keeps_threshold_checks_armed() {
"a failed or skipped summary suppresses the rest of the run"
);
}
+
+#[test]
+fn low_custom_percentage_compacts_real_history_once_and_then_makes_progress() {
+ let _faux = FAUX_TEST_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let (engine, dir) = faux_engine_with_settings(
+ &serde_json::json!({
+ "responses": vec![serde_json::json!({"text": "short response"}); 80],
+ }),
+ 16_384,
+ );
+ std::fs::write(
+ dir.path().join("agent/settings.json"),
+ serde_json::json!({"compaction": {
+ "enabled": true, "thresholdPercent": 5,
+ "reserveTokens": 16_384, "keepRecentTokens": 20_000
+ }})
+ .to_string(),
+ )
+ .unwrap();
+ let engine = std::sync::Arc::new(engine);
+ engine.register_arc();
+ let mut events = Vec::new();
+ let mut compacted = false;
+ for turn in 0..30 {
+ admit(
+ &engine,
+ format!("turn {turn} {}", "x".repeat(12_000)),
+ &mut events,
+ );
+ if let Some(EngineEvent::Compaction { event, entry }) = events
+ .iter()
+ .find(|event| matches!(event, EngineEvent::Compaction { .. }))
+ {
+ assert!(event["result"]["summary"]
+ .as_str()
+ .unwrap()
+ .contains("short response"));
+ assert!(entry["firstKeptEntryId"].is_string());
+ compacted = true;
+ break;
+ }
+ }
+ assert!(compacted, "the 5% setting ran an actual compaction");
+ let usage = events
+ .iter()
+ .filter_map(|event| match event {
+ EngineEvent::AssistantMessage(message) => message["usage"]["totalTokens"].as_u64(),
+ _ => None,
+ })
+ .next_back()
+ .unwrap();
+ assert!(
+ usage < 95_232,
+ "compaction occurred before the unchanged default trigger"
+ );
+ for turn in 0..4 {
+ admit(&engine, format!("short continuation {turn}"), &mut events);
+ }
+ let starts = events
+ .iter()
+ .filter(|event| matches!(event, EngineEvent::CompactionStart { .. }))
+ .count();
+ let ends = events
+ .iter()
+ .filter(|event| matches!(event, EngineEvent::Compaction { .. }))
+ .count();
+ assert_eq!(
+ (starts, ends),
+ (1, 1),
+ "short turns do not recompact retained history"
+ );
+ assert_eq!(
+ assistant_texts(&events).last().map(String::as_str),
+ Some("short response")
+ );
+
+ // The autonomous mirror shares the same live getter rather than a copied refresh.
+ let mut settings =
+ pa_core::settings::SettingsManager::create(dir.path(), dir.path().join("agent"));
+ settings.set_compaction_threshold_percent(75.0).unwrap();
+ let mirror = engine.autonomous_boundary.lock().unwrap().clone().unwrap();
+ let session = mirror.session.upgrade().unwrap();
+ assert_eq!(
+ session.session.compaction_settings(),
+ pa_core::session_engine::compaction::CompactionSettings {
+ threshold_percent: 75.0,
+ reserve_tokens: 16_384,
+ keep_recent_tokens: 20_000,
+ ..Default::default()
+ }
+ );
+}
diff --git a/crates/pa-daemon/src/autonomous_continuation.rs b/crates/pa-daemon/src/autonomous_continuation.rs
index 178558db19..8f674eb202 100644
--- a/crates/pa-daemon/src/autonomous_continuation.rs
+++ b/crates/pa-daemon/src/autonomous_continuation.rs
@@ -20,7 +20,7 @@ pub(crate) struct AutonomousBoundaryMirror {
pub(crate) turn_boundary:
std::sync::Arc<pa_core::session_engine::turn_boundary::TurnBoundaryRequests>,
pub(crate) agent: std::sync::Arc<pa_agent::agent::Agent>,
- pub(crate) compaction: pa_core::session_engine::compaction::CompactionSettings,
+ pub(crate) session: std::sync::Weak<pa_core::session_engine::engine::SessionEngine>,
}
impl AgentSessionEngine {
@@ -193,6 +193,9 @@ impl AgentSessionEngine {
.iter()
.filter_map(json_round_trip::<_, pa_types::session::AgentMessage>)
.collect();
+ let Some(session) = mirror.session.upgrade() else {
+ return false;
+ };
pa_core::session_engine::compaction::threshold_compaction_due(
&messages,
model.context_window,
@@ -202,7 +205,7 @@ impl AgentSessionEngine {
state.thinking_level,
),
),
- &mirror.compaction,
+ &session.session.compaction_settings(),
)
}
diff --git a/crates/pa-telemetry/src/catalog.rs b/crates/pa-telemetry/src/catalog.rs
index dc77b92671..2e27adf2a5 100644
--- a/crates/pa-telemetry/src/catalog.rs
+++ b/crates/pa-telemetry/src/catalog.rs
@@ -761,6 +761,20 @@ const AGENT_COMMAND_USED: EventRule = EventRule {
properties: &[("command_name", required(free_string(64)))],
};
+/// Adoption of the automatic compaction percentage setting; no session content.
+const AUTOCOMPACT_THRESHOLD_CHANGED: EventRule = EventRule {
+ name: "autocompact threshold changed",
+ since: 2,
+ properties: &[(
+ "threshold_percent",
+ required(PropKind::Number {
+ max: 100,
+ integer: false,
+ nullable: false,
+ }),
+ )],
+};
+
/// The onboarding journey's real stages only.
const ONBOARDING_STAGE: EventRule = EventRule {
name: "onboarding stage",
@@ -1227,6 +1241,7 @@ pub fn catalog() -> Vec<&'static EventRule> {
&AGENT_RUN_COMPLETED,
&AGENT_SESSION_ENDED,
&AGENT_COMMAND_USED,
+ &AUTOCOMPACT_THRESHOLD_CHANGED,
&ONBOARDING_STAGE,
&ONBOARDING_COMPLETED,
&AGENT_STARTUP_STAGE,
diff --git a/crates/pa-tui/src/client_settings.rs b/crates/pa-tui/src/client_settings.rs
index aaaf107c81..8de0be2dab 100644
--- a/crates/pa-tui/src/client_settings.rs
+++ b/crates/pa-tui/src/client_settings.rs
@@ -6,6 +6,13 @@
use anyhow::Result;
pub trait ClientSettings: Send + Sync {
+ /// Automatic compaction percentage ceiling; output headroom may trigger earlier.
+ fn compaction_threshold_percent(&self) -> f64;
+ /// Persist the percentage globally.
+ ///
+ /// # Errors
+ /// Returns an error for invalid percentages or failed persistence.
+ fn set_compaction_threshold_percent(&self, percent: f64) -> Result<()>;
/// `theme` (TS `getTheme`/`setTheme`).
fn theme(&self) -> Option<String>;
/// Persists `theme` to the global scope.
diff --git a/crates/pa-tui/src/session_ui/settings.rs b/crates/pa-tui/src/session_ui/settings.rs
index 9f7fba1ce5..dd943e2268 100644
--- a/crates/pa-tui/src/session_ui/settings.rs
+++ b/crates/pa-tui/src/session_ui/settings.rs
@@ -225,6 +225,7 @@ impl SessionUi {
};
// A missing settings seam keeps the TS defaults.
if let Some(settings) = &settings {
+ values.compaction_threshold_percent = settings.compaction_threshold_percent();
values.show_images = settings.show_images();
values.auto_resize_images = settings.image_auto_resize();
values.block_images = settings.block_images();
@@ -309,6 +310,17 @@ impl SessionUi {
/// the settings seam for persisted preferences.
async fn apply_settings_change(&mut self, id: &str, value: &str, view: &mut AgentView) {
match id {
+ "autocompact-threshold" => {
+ if let Some(settings) = &self.client_settings {
+ let result = value
+ .parse::<f64>()
+ .map_err(anyhow::Error::from)
+ .and_then(|percent| settings.set_compaction_threshold_percent(percent));
+ if let Err(error) = result {
+ self.error_row(&format!("{error:#}"), view);
+ }
+ }
+ }
"autocompact" => {
self.daemon_switch(
DaemonCommand::SetAutoCompaction {
diff --git a/crates/pa-tui/src/settings_menu/menu_tests.rs b/crates/pa-tui/src/settings_menu/menu_tests.rs
index 862a7b5e7b..03334682d7 100644
--- a/crates/pa-tui/src/settings_menu/menu_tests.rs
+++ b/crates/pa-tui/src/settings_menu/menu_tests.rs
@@ -52,7 +52,8 @@ fn tabs_partition_the_settings_rows() {
"steering-mode",
"follow-up-mode",
"quiet-startup",
- "warnings"
+ "warnings",
+ "autocompact-threshold"
]
),
(
@@ -416,8 +417,12 @@ fn a_paste_types_into_the_search_query_without_spaces() {
let mut menu = menu();
menu.paste("auto comp");
assert_eq!(menu.tabs[menu.tab].search.value(), "autocomp");
- assert_eq!(menu.tabs[menu.tab].filtered.len(), 1);
+ assert_eq!(menu.tabs[menu.tab].filtered.len(), 2);
assert_eq!(menu.rows[menu.tabs[menu.tab].filtered[0]].id, "autocompact");
+ assert_eq!(
+ menu.rows[menu.tabs[menu.tab].filtered[1]].id,
+ "autocompact-threshold"
+ );
}
#[test]
@@ -642,3 +647,59 @@ fn space_activates_instead_of_typing_into_the_query() {
"the sanitized Space never types into the search field"
);
}
+
+#[test]
+fn threshold_control_uses_five_point_steps_and_wraps_at_preset_boundaries() {
+ let values = SettingsCurrentValues {
+ compaction_threshold_percent: 95.0,
+ ..Default::default()
+ };
+ let mut menu = SettingsMenu::new(settings_menu_rows(&values));
+ menu.paste("threshold");
+ for (key, expected) in [
+ ("left", "90"),
+ ("left", "85"),
+ ("right", "90"),
+ ("right", "95"),
+ ("right", "100"),
+ ("right", "5"),
+ ("left", "100"),
+ ] {
+ assert_eq!(
+ menu.handle_key(key, &kb()),
+ SettingsMenuAction::Change {
+ id: "autocompact-threshold",
+ value: expected.into()
+ }
+ );
+ }
+}
+
+#[test]
+fn threshold_control_retains_off_grid_values_and_selects_neighbouring_presets() {
+ for (saved, lower, upper) in [
+ (62.5, "60", "65"),
+ (63.0, "60", "65"),
+ (1.0, "100", "5"),
+ (99.0, "95", "100"),
+ ] {
+ for (key, expected) in [("left", lower), ("right", upper)] {
+ let values = SettingsCurrentValues {
+ compaction_threshold_percent: saved,
+ ..Default::default()
+ };
+ let mut menu = SettingsMenu::new(settings_menu_rows(&values));
+ menu.paste("threshold");
+ assert!(render_text(&menu)
+ .iter()
+ .any(|row| row.contains(&saved.to_string())));
+ assert_eq!(
+ menu.handle_key(key, &kb()),
+ SettingsMenuAction::Change {
+ id: "autocompact-threshold",
+ value: expected.into()
+ }
+ );
+ }
+ }
+}
diff --git a/crates/pa-tui/src/settings_menu/mod.rs b/crates/pa-tui/src/settings_menu/mod.rs
index 2cd9ad6162..ce1291d4c9 100644
--- a/crates/pa-tui/src/settings_menu/mod.rs
+++ b/crates/pa-tui/src/settings_menu/mod.rs
@@ -134,7 +134,26 @@ pub fn settings_menu_rows(current: &SettingsCurrentValues) -> Vec<SettingsMenuRo
idle_values[1..].sort_by_key(|value| value.parse::<u32>().unwrap_or(0));
}
}
+ let percent =
+ if pa_types::compaction::is_valid_threshold_percent(current.compaction_threshold_percent) {
+ current.compaction_threshold_percent
+ } else {
+ 95.0
+ };
+ let mut thresholds: Vec<f64> = (5..=100).step_by(5).map(f64::from).collect();
+ if !thresholds.contains(&percent) {
+ thresholds.push(percent);
+ thresholds.sort_by(f64::total_cmp);
+ }
vec![
+ SettingsMenuRow {
+ id: "autocompact-threshold",
+ label: "Auto-compact threshold (%)",
+ description: "Context percentage (1–100); retained history and model output budgets bound the trigger",
+ current: percent.to_string(),
+ values: Some(thresholds.into_iter().map(|value| value.to_string()).collect()),
+ submenu: None,
+ },
SettingsMenuRow {
id: "autocompact",
label: "Auto-compact",
@@ -323,6 +342,7 @@ pub fn settings_menu_rows(current: &SettingsCurrentValues) -> Vec<SettingsMenuRo
#[derive(Debug, Clone, Default)]
pub struct SettingsCurrentValues {
pub autocompact: bool,
+ pub compaction_threshold_percent: f64,
pub show_images: bool,
pub auto_resize_images: bool,
pub block_images: bool,
diff --git a/crates/pa-tui/src/settings_menu/tabs.rs b/crates/pa-tui/src/settings_menu/tabs.rs
index 20eaf5cc5c..85e802f809 100644
--- a/crates/pa-tui/src/settings_menu/tabs.rs
+++ b/crates/pa-tui/src/settings_menu/tabs.rs
@@ -23,6 +23,7 @@ const TAB_LAYOUT: &[TabLayout] = &[
"follow-up-mode",
"quiet-startup",
"warnings",
+ "autocompact-threshold",
],
},
TabLayout {
diff --git a/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs b/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs
index 844ffc3190..80f9978774 100644
--- a/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs
+++ b/crates/pa-tui/tests/anthropic_warning_lifecycle_headless.rs
@@ -235,6 +235,13 @@ struct StubSettings {
}
impl pa_tui::client_settings::ClientSettings for StubSettings {
+ fn compaction_threshold_percent(&self) -> f64 {
+ 95.0
+ }
+ fn set_compaction_threshold_percent(&self, _percent: f64) -> Result<()> {
+ Ok(())
+ }
+
fn theme(&self) -> Option<String> {
None
}
diff --git a/crates/pa-tui/tests/chat_detail_persist_headless.rs b/crates/pa-tui/tests/chat_detail_persist_headless.rs
index a063eef95f..6c00114cb2 100644
--- a/crates/pa-tui/tests/chat_detail_persist_headless.rs
+++ b/crates/pa-tui/tests/chat_detail_persist_headless.rs
@@ -178,6 +178,13 @@ impl StubSettings {
}
impl pa_tui::client_settings::ClientSettings for StubSettings {
+ fn compaction_threshold_percent(&self) -> f64 {
+ 95.0
+ }
+ fn set_compaction_threshold_percent(&self, _percent: f64) -> Result<()> {
+ Ok(())
+ }
+
fn theme(&self) -> Option<String> {
None
}
diff --git a/crates/pa-tui/tests/esc_repeat_ladder_headless.rs b/crates/pa-tui/tests/esc_repeat_ladder_headless.rs
index 3bcf82b248..2c7fd5a27e 100644
--- a/crates/pa-tui/tests/esc_repeat_ladder_headless.rs
+++ b/crates/pa-tui/tests/esc_repeat_ladder_headless.rs
@@ -228,6 +228,13 @@ fn write_json(writer: &mut UnixStream, value: &Value) {
struct StubSettings;
impl pa_tui::client_settings::ClientSettings for StubSettings {
+ fn compaction_threshold_percent(&self) -> f64 {
+ 95.0
+ }
+ fn set_compaction_threshold_percent(&self, _percent: f64) -> Result<()> {
+ Ok(())
+ }
+
fn theme(&self) -> Option<String> {
None
}
diff --git a/crates/pa-tui/tests/factory_command_headless.rs b/crates/pa-tui/tests/factory_command_headless.rs
index d71e7aa5cd..8f8f4a1d38 100644
--- a/crates/pa-tui/tests/factory_command_headless.rs
+++ b/crates/pa-tui/tests/factory_command_headless.rs
@@ -269,6 +269,13 @@ struct RecordingSettings {
}
impl pa_tui::client_settings::ClientSettings for RecordingSettings {
+ fn compaction_threshold_percent(&self) -> f64 {
+ 95.0
+ }
+ fn set_compaction_threshold_percent(&self, _percent: f64) -> Result<()> {
+ Ok(())
+ }
+
fn theme(&self) -> Option<String> {
None
}
diff --git a/crates/pa-tui/tests/nightly_command_headless.rs b/crates/pa-tui/tests/nightly_command_headless.rs
index 4a18cf24fc..78cbbf873a 100644
--- a/crates/pa-tui/tests/nightly_command_headless.rs
+++ b/crates/pa-tui/tests/nightly_command_headless.rs
@@ -185,6 +185,13 @@ struct StubSettings {
}
impl pa_tui::client_settings::ClientSettings for StubSettings {
+ fn compaction_threshold_percent(&self) -> f64 {
+ 95.0
+ }
+ fn set_compaction_threshold_percent(&self, _percent: f64) -> Result<()> {
+ Ok(())
+ }
+
fn theme(&self) -> Option<String> {
None
}
diff --git a/crates/pa-tui/tests/settings_menu_headless.rs b/crates/pa-tui/tests/settings_menu_headless.rs
index e881fe03b4..0408be01ab 100644
--- a/crates/pa-tui/tests/settings_menu_headless.rs
+++ b/crates/pa-tui/tests/settings_menu_headless.rs
@@ -247,6 +247,13 @@ impl RecordingSettings {
}
impl pa_tui::client_settings::ClientSettings for RecordingSettings {
+ fn compaction_threshold_percent(&self) -> f64 {
+ 95.0
+ }
+ fn set_compaction_threshold_percent(&self, percent: f64) -> Result<()> {
+ self.record(&format!("threshold={percent}"))
+ }
+
fn theme(&self) -> Option<String> {
None
}
@@ -731,3 +738,22 @@ fn a_no_match_query_backspaces_away_and_space_still_cycles() {
"Space still cycles the selected row: {row}"
);
}
+
+#[test]
+fn threshold_percentage_cycles_through_the_persistence_seam() {
+ let mut steps = open_settings();
+ for character in "threshold".chars() {
+ steps.push(HeadlessStep::Key(key(KeyCode::Char(character))));
+ }
+ steps.push(HeadlessStep::Key(key(KeyCode::Right)));
+ steps.push(HeadlessStep::WaitRender {
+ needle: "› Auto-compact threshold (%)".into(),
+ timeout_ms: 5000,
+ });
+ let (frames, settings) = run_plan(steps);
+ assert_eq!(settings.log(), vec!["threshold=100"]);
+ let rows = frame_with(&frames, "› Auto-compact threshold (%)");
+ assert!(rows
+ .iter()
+ .any(|row| row.contains("Auto-compact threshold (%)") && row.contains("100")));
+}
diff --git a/crates/pa-tui/tests/skills_menu_headless.rs b/crates/pa-tui/tests/skills_menu_headless.rs
index 715f16d8fc..5e2757d5bd 100644
--- a/crates/pa-tui/tests/skills_menu_headless.rs
+++ b/crates/pa-tui/tests/skills_menu_headless.rs
@@ -272,6 +272,13 @@ impl Default for StubSettings {
}
impl pa_tui::client_settings::ClientSettings for StubSettings {
+ fn compaction_threshold_percent(&self) -> f64 {
+ 95.0
+ }
+ fn set_compaction_threshold_percent(&self, _percent: f64) -> Result<()> {
+ Ok(())
+ }
+
fn theme(&self) -> Option<String> {
None
}
diff --git a/crates/pa-tui/tests/telemetry_command_headless.rs b/crates/pa-tui/tests/telemetry_command_headless.rs
index c89ebc5a6b..c06e434fc0 100644
--- a/crates/pa-tui/tests/telemetry_command_headless.rs
+++ b/crates/pa-tui/tests/telemetry_command_headless.rs
@@ -214,6 +214,13 @@ impl StubSettings {
}
impl pa_tui::client_settings::ClientSettings for StubSettings {
+ fn compaction_threshold_percent(&self) -> f64 {
+ 95.0
+ }
+ fn set_compaction_threshold_percent(&self, _percent: f64) -> Result<()> {
+ Ok(())
+ }
+
fn theme(&self) -> Option<String> {
None
}
diff --git a/crates/pa-types/README.md b/crates/pa-types/README.md
index 8670957008..393692696b 100644
--- a/crates/pa-types/README.md
+++ b/crates/pa-types/README.md
@@ -3,6 +3,9 @@
The single shared vocabulary crate. Nothing else is shared between crates.
## Scope
+
+`compaction::is_valid_threshold_percent` is the shared percentage-domain validator
+used by settings deserialization, persistence, runtime policy, and the TUI.
Wire and domain types + serde only: AI messages/content blocks/tool calls/usage/stream events, session JSONL entry schema, daemon wire protocol messages, worker frames.
Daemon wire mechanics shared by the serving side (pa-daemon) and clients (pa-tui/pa-cli) live here because pa-tui depends on pa-types alone:
diff --git a/crates/pa-types/src/compaction.rs b/crates/pa-types/src/compaction.rs
new file mode 100644
index 0000000000..c573c8e044
--- /dev/null
+++ b/crates/pa-types/src/compaction.rs
@@ -0,0 +1,7 @@
+//! Shared vocabulary for the automatic compaction percentage setting.
+
+/// Whether a configured automatic compaction percentage is a finite value in 1–100.
+#[must_use]
+pub fn is_valid_threshold_percent(percent: f64) -> bool {
+ percent.is_finite() && (1.0..=100.0).contains(&percent)
+}
diff --git a/crates/pa-types/src/lib.rs b/crates/pa-types/src/lib.rs
index 875ed03bde..c36fa11800 100644
--- a/crates/pa-types/src/lib.rs
+++ b/crates/pa-types/src/lib.rs
@@ -7,6 +7,7 @@
//! survive a parse/serialize round trip: the re-parsed JSON must equal the original.
pub mod ai;
+pub mod compaction;
pub mod daemon;
pub mod goal;
pub mod incident;
diff --git a/scripts/review_autocompact_settings_parity.py b/scripts/review_autocompact_settings_parity.py
new file mode 100644
index 0000000000..69bf1bbab0
--- /dev/null
+++ b/scripts/review_autocompact_settings_parity.py
@@ -0,0 +1,92 @@
+#!/usr/bin/env python3
+"""Observe /settings in pinned TS and Rust binaries with the same PTY input.
+
+Keep full frames and wire commands, compare the existing auto-compaction toggle,
+and record the requested Rust-only percentage row as an explicit feature addition.
+No real inference, user home, or production daemon is used.
+"""
+import argparse
+import difflib
+import json
+import os
+import re
+from pathlib import Path
+import tempfile
+
+from review_draft_disconnect_parity import (
+ Supervisor, Terminal, actual_hello, digest, env_for,
+)
+
+
+def observe(binary, kind, root):
+ root.mkdir()
+ env = env_for(root, kind)
+ hello = actual_hello(binary, root, env)
+ server = Supervisor(root / 'ui.sock', hello, 'settings', root)
+ terminal = None
+ result = {'binary_sha256': digest(binary), 'executed': False}
+ try:
+ terminal = Terminal([str(binary), '--daemon-socket', str(server.path)], root, env)
+ terminal.wait('initial attach', lambda: server.attaches > 0 and bool(terminal.screen.text().strip()), server)
+ terminal.send('/settings')
+ terminal.wait('settings typed', lambda: '/settings' in terminal.screen.text(), server)
+ terminal.send('\r')
+ terminal.wait('settings menu', lambda: 'Auto-compact' in terminal.screen.text(), server)
+ result['settings_frame'] = terminal.screen.text()
+ terminal.send('\r')
+ terminal.wait('toggle delivered', lambda: any(c.get('type') == 'set_auto_compaction' for c in server.commands), server)
+ terminal.wait('toggle rendered', lambda: any('Auto-compact' in row and 'true' in row for row in terminal.screen.text().splitlines()), server)
+ result['toggle_frame'] = terminal.screen.text()
+ result['toggle_rows'] = [re.sub(r'\s+', ' ', row.strip().lstrip('›> ').strip()) for row in terminal.screen.text().splitlines()
+ if 'Auto-compact' in row and 'threshold' not in row]
+ result['toggle_payloads'] = [json.dumps({k: c[k] for k in ('type', 'activeSessionId', 'enabled')}, sort_keys=True)
+ for c in server.commands if c.get('type') == 'set_auto_compaction']
+ if kind == 'rust':
+ # Search for the added row so other General settings can evolve independently.
+ terminal.send('threshold')
+ terminal.wait('percentage focused', lambda: any(row.strip().startswith('› Auto-compact threshold (%)') for row in terminal.screen.text().splitlines()), server)
+ result['percentage_frame'] = terminal.screen.text()
+ terminal.send('\r')
+ path = root / 'agent/settings.json'
+ terminal.wait('percentage persisted', lambda: json.loads(path.read_text()).get('compaction', {}).get('thresholdPercent') == 100, server)
+ terminal.wait('percentage rendered', lambda: any('threshold (%)' in row and '100' in row for row in terminal.screen.text().splitlines()), server)
+ result['changed_percentage_frame'] = terminal.screen.text()
+ result['saved_percentage'] = json.loads(path.read_text())['compaction']['thresholdPercent']
+ result['executed'] = True
+ except Exception as error:
+ result['error'] = str(error)
+ finally:
+ if terminal:
+ terminal.close()
+ result['terminal_raw_hex'] = terminal.raw.hex()
+ server.close()
+ result['commands'] = server.commands
+ result['fixture_errors'] = server.errors
+ return result
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--receipt', type=Path, required=True)
+ args = parser.parse_args()
+ receipt = {'intended_addition': 'Rust adds the requested 1–100% auto-compaction percentage row; TS 0.9.8 has no such row.',
+ 'existing_layout_difference': 'Rust already groups settings into tabs; the full frame diff preserves that difference.',
+ 'scope': 'Real client binaries against an isolated synthetic daemon; model compaction execution is covered by Rust tests.',
+ 'results': {}}
+ with tempfile.TemporaryDirectory(prefix='autocompact-parity-') as directory:
+ root = Path(directory)
+ for kind, name in [('ts', 'PA_TS_BINARY'), ('rust', 'PA_RUST_BINARY')]:
+ receipt['results'][kind] = observe(Path(os.environ[name]).resolve(), kind, root / kind)
+ ts, rust = (receipt['results'][kind] for kind in ('ts', 'rust'))
+ receipt['frame_diff'] = list(difflib.unified_diff(ts.get('settings_frame', '').splitlines(), rust.get('settings_frame', '').splitlines(), fromfile='TS', tofile='Rust'))
+ receipt['toggle_wire_equal'] = ts.get('toggle_payloads') == rust.get('toggle_payloads') and bool(ts.get('toggle_payloads'))
+ receipt['toggle_rows_equal'] = ts.get('toggle_rows') == rust.get('toggle_rows') and bool(ts.get('toggle_rows'))
+ receipt['passed'] = all(result.get('executed') and not result['fixture_errors'] for result in (ts, rust)) and receipt['toggle_wire_equal'] and receipt['toggle_rows_equal'] and rust.get('saved_percentage') == 100
+ args.receipt.parent.mkdir(parents=True, exist_ok=True)
+ args.receipt.write_text(json.dumps(receipt, indent=2) + '\n')
+ print(json.dumps({key: receipt[key] for key in ('passed', 'toggle_wire_equal', 'toggle_rows_equal')}))
+ return 0 if receipt['passed'] else 1
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/scripts/review_draft_disconnect_parity.py b/scripts/review_draft_disconnect_parity.py
index f4afd4966f..f40ab2e445 100644
--- a/scripts/review_draft_disconnect_parity.py
+++ b/scripts/review_draft_disconnect_parity.py
@@ -389,6 +389,10 @@ class Supervisor:
response["data"]["messageCount"] = len(self.messages)
elif name == "get_mcp_connections": response["data"] = {"connections": []}
elif name == "detach": response["data"] = {}
+ elif name == "set_auto_compaction":
+ if not isinstance(command.get("enabled"), bool):
+ raise RuntimeError("set_auto_compaction requires a boolean")
+ response.pop("data", None)
else:
self.errors.append(f"unexpected command: {name}")
response.update(success=False, error=f"Unsupported fixture command: {name}")