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
56 changes: 55 additions & 1 deletion .github/workflows/patched-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,51 @@ jobs:
"agents::state_machine::ops_self_compact::tests::test_compacted_turns_before_derivation" \
"agents::state_machine::ops_self_compact::tests::test_self_compact_turn_limit_operation" \
"agents::state_machine::ops_self_compact::tests::test_finalize_cancellation_guards" \
"agents::state_machine::ops_self_compact::tests::test_finalize_cancellation_skips_prompt_with_persisted_outcome"
"agents::state_machine::ops_self_compact::tests::test_finalize_cancellation_skips_prompt_with_persisted_outcome" \
"prompt_template::tests::compaction_rolling_template_is_registered" \
"context_mgmt::rolling::tests::rolling_backoff_cases" \
"context_mgmt::rolling::tests::rolling_calibrated_ratio_clamps" \
"context_mgmt::rolling::tests::rolling_check_backed_off_returns_none" \
"context_mgmt::rolling::tests::rolling_check_cheap_path_matches_full_estimate" \
"context_mgmt::rolling::tests::rolling_check_under_budget_returns_none" \
"context_mgmt::rolling::tests::rolling_cut_ignores_agent_invisible_history" \
"context_mgmt::rolling::tests::rolling_cut_includes_old_compact_summary" \
"context_mgmt::rolling::tests::rolling_cut_nothing_to_fold" \
"context_mgmt::rolling::tests::rolling_cut_pairing_violation_is_error" \
"context_mgmt::rolling::tests::rolling_cut_previous_memory_detected_and_excluded_from_progress" \
"context_mgmt::rolling::tests::rolling_cut_ratio_scales_tail" \
"context_mgmt::rolling::tests::rolling_cut_single_turn_bigger_than_tail" \
"context_mgmt::rolling::tests::rolling_cut_skips_turn_context_and_steer_and_nudge" \
"context_mgmt::rolling::tests::rolling_cut_tail_starts_at_genuine_prompt" \
"context_mgmt::rolling::tests::rolling_decide_cases" \
"context_mgmt::rolling::tests::rolling_estimate_cases" \
"context_mgmt::rolling::tests::rolling_fold_round_trip" \
"context_mgmt::rolling::tests::rolling_fold_rows_cut_out_of_bounds" \
"context_mgmt::rolling::tests::rolling_fold_rows_rejects_empty_folded" \
"context_mgmt::rolling::tests::rolling_fold_rows_rejects_folded_at_or_after_cut" \
"context_mgmt::rolling::tests::rolling_fold_rows_rejects_missing_id" \
"context_mgmt::rolling::tests::rolling_fold_rows_shape" \
"context_mgmt::rolling::tests::rolling_genuine_prompt_visibility_and_types" \
"context_mgmt::rolling::tests::rolling_history_skips_turn_context_and_previous_memory" \
"context_mgmt::rolling::tests::rolling_memory_failures" \
"context_mgmt::rolling::tests::rolling_memory_large_end_turn_is_success" \
"context_mgmt::rolling::tests::rolling_memory_neutralizes_previous_memory_closing_tags" \
"context_mgmt::rolling::tests::rolling_memory_refusal_retries_once_without_tool_responses" \
"context_mgmt::rolling::tests::rolling_memory_request_shape" \
"context_mgmt::rolling::tests::rolling_render_line_stamps_utc_and_strips_only_leading_prefix" \
"context_mgmt::rolling::tests::rolling_render_neutralizes_closing_tags" \
"context_mgmt::rolling::tests::rolling_resolve_absent_both_env" \
"context_mgmt::rolling::tests::rolling_resolve_absent_no_env" \
"context_mgmt::rolling::tests::rolling_resolve_absent_only_one_env" \
"context_mgmt::rolling::tests::rolling_resolve_invalid_object" \
"context_mgmt::rolling::tests::rolling_resolve_null_both_env" \
"context_mgmt::rolling::tests::rolling_resolve_object_key" \
"context_mgmt::rolling::tests::rolling_resolve_unparsable_env" \
"context_mgmt::rolling::tests::rolling_settings_validate_floors" \
"context_mgmt::rolling::tests::rolling_settings_write_null" \
"context_mgmt::rolling::tests::rolling_state_default_absent" \
"context_mgmt::rolling::tests::rolling_state_invalid_defaults" \
"context_mgmt::rolling::tests::rolling_state_roundtrip"

run_exact_tests --release -p goose --features "$F" --test self_compact -- \
"test_happy_path_self_compact" \
Expand Down Expand Up @@ -181,6 +225,16 @@ jobs:
"test_session_settings_idempotent_prompts_byte_identical" \
"test_session_settings_templated_recipe_renders_consistently"

run_exact_tests --release -p goose --features "$F" --test rolling_memory -- \
"rolling_fold_happens_and_next_call_sees_memory_plus_tail" \
"rolling_off_by_default_no_memory_call" \
"rolling_skips_threshold_auto_compaction" \
"rolling_failure_proceeds_and_counts" \
"rolling_metrics_use_retained_form" \
"rolling_cancel_during_memory_call_drops_cleanly" \
"rolling_decide_skip_yields_no_folding_notice_and_no_memory_call" \
"rolling_fires_only_once_across_turns"

run_exact_tests --release -p goose-provider-types --lib -- \
"formats::anthropic::tests::native_claude_thinking_carries_display_and_block_binding" \
"formats::anthropic::tests::summarized_thinking_round_trips_with_its_signature" \
Expand Down
112 changes: 110 additions & 2 deletions crates/goose-sdk-types/src/custom_requests/session_settings.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,43 @@
// Modified by Jonathan Mohrbacher, 2026: SetSessionSettingsRequest pins a session's cache TTL and recipe.
// Modified by Jonathan Mohrbacher, 2026: SetSessionSettingsRequest pins a session's cache TTL, recipe and rolling memory.
use agent_client_protocol::JsonRpcRequest;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::{EmptyResponse, RecipeDto};

/// Pin a session's prompt-cache TTL and recipe, persisted on the session row.
/// Distinguishes an absent field (None) from an explicit null (Some(None)).
fn double_option<'de, D, T>(de: D) -> Result<Option<Option<T>>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de>,
{
Option::<T>::deserialize(de).map(Some)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RollingMemoryDto {
pub budget_tokens: u32,
pub tail_tokens: u32,
}

impl RollingMemoryDto {
/// 0 < tail < budget, budget >= 10_000, tail >= 1_000. Returns a message for invalid_params otherwise.
pub fn validate(&self) -> Result<(), String> {
if self.tail_tokens < 1_000 {
return Err("tailTokens must be at least 1000".to_string());
}
if self.budget_tokens < 10_000 {
return Err("budgetTokens must be at least 10000".to_string());
}
if self.tail_tokens >= self.budget_tokens {
return Err("tailTokens must be less than budgetTokens".to_string());
}
Ok(())
}
}

/// Pin a session's prompt-cache TTL, recipe and rolling memory, persisted on the session row.
///
/// The recipe is stored on the session and read every turn: its `title`,
/// `instructions` and `response` take effect. Its `settings`, `extensions`,
Expand All @@ -23,4 +55,80 @@ pub struct SetSessionSettingsRequest {
pub cache_ttl: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recipe: Option<RecipeDto>,
/// Rolling memory for this session. Absent: unchanged. null: off.
#[serde(
default,
deserialize_with = "double_option",
skip_serializing_if = "Option::is_none"
)]
#[schemars(with = "Option<RollingMemoryDto>")]
pub rolling_memory: Option<Option<RollingMemoryDto>>,
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn settings_request_rolling_memory_absent() {
let req: SetSessionSettingsRequest =
serde_json::from_str(r#"{"sessionId":"abc"}"#).unwrap();
assert_eq!(req.rolling_memory, None);
}

#[test]
fn settings_request_rolling_memory_null() {
let req: SetSessionSettingsRequest =
serde_json::from_str(r#"{"sessionId":"abc","rollingMemory":null}"#).unwrap();
assert_eq!(req.rolling_memory, Some(None));
}

#[test]
fn settings_request_rolling_memory_object() {
let req: SetSessionSettingsRequest = serde_json::from_str(
r#"{"sessionId":"abc","rollingMemory":{"budgetTokens":10000,"tailTokens":1000}}"#,
)
.unwrap();
assert_eq!(
req.rolling_memory,
Some(Some(RollingMemoryDto {
budget_tokens: 10000,
tail_tokens: 1000,
}))
);
}

#[test]
fn rolling_memory_dto_validation() {
assert!(RollingMemoryDto {
budget_tokens: 10_000,
tail_tokens: 1_000
}
.validate()
.is_ok());
assert!(RollingMemoryDto {
budget_tokens: 9_999,
tail_tokens: 1_000
}
.validate()
.is_err());
assert!(RollingMemoryDto {
budget_tokens: 10_000,
tail_tokens: 999
}
.validate()
.is_err());
assert!(RollingMemoryDto {
budget_tokens: 10_000,
tail_tokens: 10_000
}
.validate()
.is_err());
assert!(RollingMemoryDto {
budget_tokens: 10_000,
tail_tokens: 11_000
}
.validate()
.is_err());
}
}
30 changes: 29 additions & 1 deletion crates/goose/acp-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -832,12 +832,23 @@
"type": "null"
}
]
},
"rollingMemory": {
"anyOf": [
{
"$ref": "#/$defs/RollingMemoryDto"
},
{
"type": "null"
}
],
"description": "Rolling memory for this session. Absent: unchanged. null: off."
}
},
"required": [
"sessionId"
],
"description": "Pin a session's prompt-cache TTL and recipe, persisted on the session row.\n\nThe recipe is stored on the session and read every turn: its `title`,\n`instructions` and `response` take effect. Its `settings`, `extensions`,\n`prompt` and `parameters` are ignored, `retry` and `sub_recipes` are\ndropped, and the session keeps its model.",
"description": "Pin a session's prompt-cache TTL, recipe and rolling memory, persisted on the session row.\n\nThe recipe is stored on the session and read every turn: its `title`,\n`instructions` and `response` take effect. Its `settings`, `extensions`,\n`prompt` and `parameters` are ignored, `retry` and `sub_recipes` are\ndropped, and the session keeps its model.",
"x-side": "agent",
"x-method": "_goose/unstable/session/settings/set"
},
Expand Down Expand Up @@ -9160,6 +9171,23 @@
}
],
"x-docs-ignore": true
},
"RollingMemoryDto": {
"type": "object",
"properties": {
"budgetTokens": {
"type": "integer",
"minimum": 0
},
"tailTokens": {
"type": "integer",
"minimum": 0
}
},
"required": [
"budgetTokens",
"tailTokens"
]
}
},
"anyOf": [
Expand Down
19 changes: 18 additions & 1 deletion crates/goose/src/acp/server/session_settings.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Modified by Jonathan Mohrbacher, 2026: _goose/unstable/session/settings/set pins a session's cache TTL and recipe; session/prompt _meta.goose.maxTurns bounds the run.
// Modified by Jonathan Mohrbacher, 2026: _goose/unstable/session/settings/set pins a session's cache TTL, recipe and rolling memory; session/prompt _meta.goose.maxTurns bounds the run.
use agent_client_protocol::schema::v1::Meta;

use super::{AcpConnection, ResultExt};
Expand Down Expand Up @@ -116,6 +116,13 @@ impl AcpConnection {
.map(normalized_cache_ttl)
.transpose()?;

if let Some(Some(dto)) = &req.rolling_memory {
if let Err(msg) = dto.validate() {
return Err(agent_client_protocol::Error::invalid_params()
.data(format!("invalid rollingMemory: {msg}")));
}
}

let mut session = self
.services
.session_manager
Expand Down Expand Up @@ -161,6 +168,16 @@ impl AcpConnection {
}
}

if let Some(v) = req.rolling_memory {
crate::context_mgmt::rolling::persist_settings(
&self.services.session_manager,
session_id,
v.map(Into::into),
)
.await
.internal_err_ctx("Failed to persist rolling memory settings to session")?;
}

let Some(recipe) = recipe else {
self.render_stored_recipe_template(&mut session).await?;
return Ok(EmptyResponse {});
Expand Down
4 changes: 3 additions & 1 deletion crates/goose/src/agents/state_machine/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Modified by Jonathan Mohrbacher, 2026: export retry and compaction failure checks for turn errors; self-compaction operation.
// Modified by Jonathan Mohrbacher, 2026: export retry and compaction failure checks for turn errors; self-compaction operation; rolling memory operation.
//! Runs an ordered, re-entrant pipeline over persisted conversation state.
//!
//! Callers persist incoming messages, construct `Step`s from their own operations,
Expand All @@ -19,6 +19,7 @@ mod ops_project;
mod ops_recipe;
mod ops_remaining_tool_calls;
mod ops_retry;
mod ops_rolling_memory;
pub mod ops_self_compact;
mod ops_skills;
mod ops_status;
Expand Down Expand Up @@ -73,6 +74,7 @@ pub(super) use ops_remaining_tool_calls::RemainingToolCallsOperation;
pub(super) use ops_remaining_tool_calls::UNCLAIMED_TOOL_ERROR;
pub(crate) use ops_retry::is_retry_failure_message;
pub(super) use ops_retry::RetryOperation;
pub(super) use ops_rolling_memory::RollingMemoryOperation;
pub(super) use ops_self_compact::{SelfCompactOperation, SelfCompactTurnLimitOperation};
pub(super) use ops_skills::{GooseSkillSource, NO_SKILLS_HELP};
pub(super) use ops_status::StatusOperation;
Expand Down
27 changes: 16 additions & 11 deletions crates/goose/src/agents/state_machine/ops_compaction.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Modified by Jonathan Mohrbacher, 2026: compaction failure messages are recognisable as turn errors.
// Modified by Jonathan Mohrbacher, 2026: compaction failure messages are recognisable as turn errors; skip proactive auto-compaction when rolling memory is on for the session.
//! Compacts conversation history when it is too large for the configured context window.

use std::sync::Arc;
Expand Down Expand Up @@ -193,16 +193,21 @@ impl Operation<Session, GooseEffect> for CompactionOperation {
if context_errors > MAX_CONTEXT_ERROR_COMPACTIONS {
return not_applicable();
}
} else if proactive_compaction_tokens(
session,
conversation,
self.context_limit,
self.threshold,
)
.await?
.is_none()
{
return not_applicable();
} else {
if crate::context_mgmt::rolling::is_on(session) {
return not_applicable();
}
if proactive_compaction_tokens(
session,
conversation,
self.context_limit,
self.threshold,
)
.await?
.is_none()
{
return not_applicable();
}
}

let conversation_with_hidden_error;
Expand Down
Loading
Loading