Skip to content

Commit e6e9dee

Browse files
committed
[NO-JIRA] Rolling memory on the state machine: fold older history at turn start (R12)
Ports rolling memory from the v1.54 legacy loop to the 1.60 state machine pipeline as RollingMemoryOperation. Design summary: - Operation timing: Runs at turn start when `messages_since_kickoff` has length 1 (the kickoff user prompt). - Estimation context: `prepare_system_and_tools` approximates the inference system prompt using PromptManager with session recipe instructions and project instructions, along with tools resolved via `services.current_session_snapshot`. This closely approximates the actual inference request for token counting. - Once-per-turn guard: Combination of durable message metadata operation note (`rolling_memory.folded = true`) applied via `SetMessageOperationNote` on the kickoff message, plus an in-memory `folded_turns` set on `RollingMemoryOperation` that records evaluated kickoff IDs across all paths (fold, not needed, under budget, error) to prevent duplicate runs across state machine steps or loops in the same turn. - Compaction gating: Proactive auto-compaction (`ops_compaction.rs`) and tool pair summarization (`ops_tool_pair_compaction.rs`) are skipped when rolling memory is active (`rolling::is_on(session)`). - Session settings & ACP: Added `rollingMemory` (budgetTokens, tailTokens) to `SetSessionSettingsRequest` in `goose-sdk-types`, `acp-schema.json`, and ACP server handlers. Behaviour changed from v1.54: - Integrated as a state machine `Operation` returning `GooseEffect`s rather than controlling the agent loop directly. - `rolling::execute_fold` no longer directly saves compacted conversations or records metrics; instead, the operation emits `GooseEffect::CompactConversation` with usage and `SetMessageOperationNote`, preventing double-counting. - `session_manager.rs` remains untouched upstream; test inspection of the usage ledger connects directly to the sqlite database via `open_test_db()`. Tests: - 44 unit tests in `context_mgmt::rolling` and `prompt_template` - 8 integration tests in `tests/rolling_memory.rs` - 6 tests in `tests/acp_session_settings_test.rs` - 9 tests in `goose-sdk-types` - All tests verified and listed in `.github/workflows/patched-test.yml` X-Shepherd-Wake: #30
1 parent d73dc1f commit e6e9dee

15 files changed

Lines changed: 4803 additions & 21 deletions

File tree

‎.github/workflows/patched-test.yml‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,51 @@ jobs:
108108
"agents::mcp_startup_timeout::tests::test_mcp_client_startup_timeout_discover_lifecycle" \
109109
"agents::mcp_startup_timeout::tests::test_mcp_client_startup_timeout_initialize_lifecycle" \
110110
"agents::extension_manager::stdio::startup_tests::test_mcp_client_startup_timeout_stdio_kills_process_group" \
111-
"agents::extension_manager::stdio::startup_tests::test_mcp_client_startup_timeout_stdio_abandoned_start_kills_process_group"
111+
"agents::extension_manager::stdio::startup_tests::test_mcp_client_startup_timeout_stdio_abandoned_start_kills_process_group" \
112+
"prompt_template::tests::compaction_rolling_template_is_registered" \
113+
"context_mgmt::rolling::tests::rolling_backoff_cases" \
114+
"context_mgmt::rolling::tests::rolling_calibrated_ratio_clamps" \
115+
"context_mgmt::rolling::tests::rolling_check_backed_off_returns_none" \
116+
"context_mgmt::rolling::tests::rolling_check_cheap_path_matches_full_estimate" \
117+
"context_mgmt::rolling::tests::rolling_check_under_budget_returns_none" \
118+
"context_mgmt::rolling::tests::rolling_cut_ignores_agent_invisible_history" \
119+
"context_mgmt::rolling::tests::rolling_cut_includes_old_compact_summary" \
120+
"context_mgmt::rolling::tests::rolling_cut_nothing_to_fold" \
121+
"context_mgmt::rolling::tests::rolling_cut_pairing_violation_is_error" \
122+
"context_mgmt::rolling::tests::rolling_cut_previous_memory_detected_and_excluded_from_progress" \
123+
"context_mgmt::rolling::tests::rolling_cut_ratio_scales_tail" \
124+
"context_mgmt::rolling::tests::rolling_cut_single_turn_bigger_than_tail" \
125+
"context_mgmt::rolling::tests::rolling_cut_skips_turn_context_and_steer_and_nudge" \
126+
"context_mgmt::rolling::tests::rolling_cut_tail_starts_at_genuine_prompt" \
127+
"context_mgmt::rolling::tests::rolling_decide_cases" \
128+
"context_mgmt::rolling::tests::rolling_estimate_cases" \
129+
"context_mgmt::rolling::tests::rolling_fold_round_trip" \
130+
"context_mgmt::rolling::tests::rolling_fold_rows_cut_out_of_bounds" \
131+
"context_mgmt::rolling::tests::rolling_fold_rows_rejects_empty_folded" \
132+
"context_mgmt::rolling::tests::rolling_fold_rows_rejects_folded_at_or_after_cut" \
133+
"context_mgmt::rolling::tests::rolling_fold_rows_rejects_missing_id" \
134+
"context_mgmt::rolling::tests::rolling_fold_rows_shape" \
135+
"context_mgmt::rolling::tests::rolling_genuine_prompt_visibility_and_types" \
136+
"context_mgmt::rolling::tests::rolling_history_skips_turn_context_and_previous_memory" \
137+
"context_mgmt::rolling::tests::rolling_memory_failures" \
138+
"context_mgmt::rolling::tests::rolling_memory_large_end_turn_is_success" \
139+
"context_mgmt::rolling::tests::rolling_memory_neutralizes_previous_memory_closing_tags" \
140+
"context_mgmt::rolling::tests::rolling_memory_refusal_retries_once_without_tool_responses" \
141+
"context_mgmt::rolling::tests::rolling_memory_request_shape" \
142+
"context_mgmt::rolling::tests::rolling_render_line_stamps_utc_and_strips_only_leading_prefix" \
143+
"context_mgmt::rolling::tests::rolling_render_neutralizes_closing_tags" \
144+
"context_mgmt::rolling::tests::rolling_resolve_absent_both_env" \
145+
"context_mgmt::rolling::tests::rolling_resolve_absent_no_env" \
146+
"context_mgmt::rolling::tests::rolling_resolve_absent_only_one_env" \
147+
"context_mgmt::rolling::tests::rolling_resolve_invalid_object" \
148+
"context_mgmt::rolling::tests::rolling_resolve_null_both_env" \
149+
"context_mgmt::rolling::tests::rolling_resolve_object_key" \
150+
"context_mgmt::rolling::tests::rolling_resolve_unparsable_env" \
151+
"context_mgmt::rolling::tests::rolling_settings_validate_floors" \
152+
"context_mgmt::rolling::tests::rolling_settings_write_null" \
153+
"context_mgmt::rolling::tests::rolling_state_default_absent" \
154+
"context_mgmt::rolling::tests::rolling_state_invalid_defaults" \
155+
"context_mgmt::rolling::tests::rolling_state_roundtrip"
112156
113157
run_exact_tests --release -p goose --features "$F" --test acp_server_test -- \
114158
"test_prompt_reports_context_error_when_compaction_limit_is_exhausted" \
@@ -123,6 +167,16 @@ jobs:
123167
"test_session_settings_idempotent_prompts_byte_identical" \
124168
"test_session_settings_templated_recipe_renders_consistently"
125169
170+
run_exact_tests --release -p goose --features "$F" --test rolling_memory -- \
171+
"rolling_fold_happens_and_next_call_sees_memory_plus_tail" \
172+
"rolling_off_by_default_no_memory_call" \
173+
"rolling_skips_threshold_auto_compaction" \
174+
"rolling_failure_proceeds_and_counts" \
175+
"rolling_metrics_use_retained_form" \
176+
"rolling_cancel_during_memory_call_drops_cleanly" \
177+
"rolling_decide_skip_yields_no_folding_notice_and_no_memory_call" \
178+
"rolling_fires_only_once_across_turns"
179+
126180
run_exact_tests --release -p goose-provider-types --lib -- \
127181
"formats::anthropic::tests::native_claude_thinking_carries_display_and_block_binding" \
128182
"formats::anthropic::tests::summarized_thinking_round_trips_with_its_signature" \

‎crates/goose-sdk-types/src/custom_requests/session_settings.rs‎

Lines changed: 110 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,43 @@
1-
// Modified by Jonathan Mohrbacher, 2026: SetSessionSettingsRequest pins a session's cache TTL and recipe.
1+
// Modified by Jonathan Mohrbacher, 2026: SetSessionSettingsRequest pins a session's cache TTL, recipe and rolling memory.
22
use agent_client_protocol::JsonRpcRequest;
33
use schemars::JsonSchema;
44
use serde::{Deserialize, Serialize};
55

66
use super::{EmptyResponse, RecipeDto};
77

8-
/// Pin a session's prompt-cache TTL and recipe, persisted on the session row.
8+
/// Distinguishes an absent field (None) from an explicit null (Some(None)).
9+
fn double_option<'de, D, T>(de: D) -> Result<Option<Option<T>>, D::Error>
10+
where
11+
D: serde::Deserializer<'de>,
12+
T: serde::Deserialize<'de>,
13+
{
14+
Option::<T>::deserialize(de).map(Some)
15+
}
16+
17+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
18+
#[serde(rename_all = "camelCase")]
19+
pub struct RollingMemoryDto {
20+
pub budget_tokens: u32,
21+
pub tail_tokens: u32,
22+
}
23+
24+
impl RollingMemoryDto {
25+
/// 0 < tail < budget, budget >= 10_000, tail >= 1_000. Returns a message for invalid_params otherwise.
26+
pub fn validate(&self) -> Result<(), String> {
27+
if self.tail_tokens < 1_000 {
28+
return Err("tailTokens must be at least 1000".to_string());
29+
}
30+
if self.budget_tokens < 10_000 {
31+
return Err("budgetTokens must be at least 10000".to_string());
32+
}
33+
if self.tail_tokens >= self.budget_tokens {
34+
return Err("tailTokens must be less than budgetTokens".to_string());
35+
}
36+
Ok(())
37+
}
38+
}
39+
40+
/// Pin a session's prompt-cache TTL, recipe and rolling memory, persisted on the session row.
941
///
1042
/// The recipe is stored on the session and read every turn: its `title`,
1143
/// `instructions` and `response` take effect. Its `settings`, `extensions`,
@@ -23,4 +55,80 @@ pub struct SetSessionSettingsRequest {
2355
pub cache_ttl: Option<String>,
2456
#[serde(default, skip_serializing_if = "Option::is_none")]
2557
pub recipe: Option<RecipeDto>,
58+
/// Rolling memory for this session. Absent: unchanged. null: off.
59+
#[serde(
60+
default,
61+
deserialize_with = "double_option",
62+
skip_serializing_if = "Option::is_none"
63+
)]
64+
#[schemars(with = "Option<RollingMemoryDto>")]
65+
pub rolling_memory: Option<Option<RollingMemoryDto>>,
66+
}
67+
68+
#[cfg(test)]
69+
mod tests {
70+
use super::*;
71+
72+
#[test]
73+
fn settings_request_rolling_memory_absent() {
74+
let req: SetSessionSettingsRequest =
75+
serde_json::from_str(r#"{"sessionId":"abc"}"#).unwrap();
76+
assert_eq!(req.rolling_memory, None);
77+
}
78+
79+
#[test]
80+
fn settings_request_rolling_memory_null() {
81+
let req: SetSessionSettingsRequest =
82+
serde_json::from_str(r#"{"sessionId":"abc","rollingMemory":null}"#).unwrap();
83+
assert_eq!(req.rolling_memory, Some(None));
84+
}
85+
86+
#[test]
87+
fn settings_request_rolling_memory_object() {
88+
let req: SetSessionSettingsRequest = serde_json::from_str(
89+
r#"{"sessionId":"abc","rollingMemory":{"budgetTokens":10000,"tailTokens":1000}}"#,
90+
)
91+
.unwrap();
92+
assert_eq!(
93+
req.rolling_memory,
94+
Some(Some(RollingMemoryDto {
95+
budget_tokens: 10000,
96+
tail_tokens: 1000,
97+
}))
98+
);
99+
}
100+
101+
#[test]
102+
fn rolling_memory_dto_validation() {
103+
assert!(RollingMemoryDto {
104+
budget_tokens: 10_000,
105+
tail_tokens: 1_000
106+
}
107+
.validate()
108+
.is_ok());
109+
assert!(RollingMemoryDto {
110+
budget_tokens: 9_999,
111+
tail_tokens: 1_000
112+
}
113+
.validate()
114+
.is_err());
115+
assert!(RollingMemoryDto {
116+
budget_tokens: 10_000,
117+
tail_tokens: 999
118+
}
119+
.validate()
120+
.is_err());
121+
assert!(RollingMemoryDto {
122+
budget_tokens: 10_000,
123+
tail_tokens: 10_000
124+
}
125+
.validate()
126+
.is_err());
127+
assert!(RollingMemoryDto {
128+
budget_tokens: 10_000,
129+
tail_tokens: 11_000
130+
}
131+
.validate()
132+
.is_err());
133+
}
26134
}

‎crates/goose/acp-schema.json‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -832,12 +832,23 @@
832832
"type": "null"
833833
}
834834
]
835+
},
836+
"rollingMemory": {
837+
"anyOf": [
838+
{
839+
"$ref": "#/$defs/RollingMemoryDto"
840+
},
841+
{
842+
"type": "null"
843+
}
844+
],
845+
"description": "Rolling memory for this session. Absent: unchanged. null: off."
835846
}
836847
},
837848
"required": [
838849
"sessionId"
839850
],
840-
"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.",
851+
"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.",
841852
"x-side": "agent",
842853
"x-method": "_goose/unstable/session/settings/set"
843854
},
@@ -9111,6 +9122,23 @@
91119122
}
91129123
],
91139124
"x-docs-ignore": true
9125+
},
9126+
"RollingMemoryDto": {
9127+
"type": "object",
9128+
"properties": {
9129+
"budgetTokens": {
9130+
"type": "integer",
9131+
"minimum": 0
9132+
},
9133+
"tailTokens": {
9134+
"type": "integer",
9135+
"minimum": 0
9136+
}
9137+
},
9138+
"required": [
9139+
"budgetTokens",
9140+
"tailTokens"
9141+
]
91149142
}
91159143
},
91169144
"anyOf": [

‎crates/goose/src/acp/server/session_settings.rs‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// 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.
1+
// 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.
22
use agent_client_protocol::schema::v1::Meta;
33

44
use super::{AcpConnection, ResultExt};
@@ -116,6 +116,13 @@ impl AcpConnection {
116116
.map(normalized_cache_ttl)
117117
.transpose()?;
118118

119+
if let Some(Some(dto)) = &req.rolling_memory {
120+
if let Err(msg) = dto.validate() {
121+
return Err(agent_client_protocol::Error::invalid_params()
122+
.data(format!("invalid rollingMemory: {msg}")));
123+
}
124+
}
125+
119126
let mut session = self
120127
.services
121128
.session_manager
@@ -161,6 +168,24 @@ impl AcpConnection {
161168
}
162169
}
163170

171+
if let Some(v) = req.rolling_memory {
172+
let session = self
173+
.services
174+
.session_manager
175+
.get_session(session_id, false)
176+
.await
177+
.internal_err_ctx("Failed to re-read session")?;
178+
let mut data = session.extension_data;
179+
crate::context_mgmt::rolling::write_settings(&mut data, v.map(Into::into));
180+
self.services
181+
.session_manager
182+
.update(session_id)
183+
.extension_data(data)
184+
.apply()
185+
.await
186+
.internal_err_ctx("Failed to persist rolling memory settings to session")?;
187+
}
188+
164189
let Some(recipe) = recipe else {
165190
self.render_stored_recipe_template(&mut session).await?;
166191
return Ok(EmptyResponse {});

‎crates/goose/src/agents/state_machine/mod.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Modified by Jonathan Mohrbacher, 2026: export retry and compaction failure checks for turn errors.
1+
// Modified by Jonathan Mohrbacher, 2026: export retry and compaction failure checks for turn errors; rolling memory operation.
22
//! Runs an ordered, re-entrant pipeline over persisted conversation state.
33
//!
44
//! Callers persist incoming messages, construct `Step`s from their own operations,
@@ -19,6 +19,7 @@ mod ops_project;
1919
mod ops_recipe;
2020
mod ops_remaining_tool_calls;
2121
mod ops_retry;
22+
mod ops_rolling_memory;
2223
mod ops_skills;
2324
mod ops_status;
2425
mod ops_stop_hook;
@@ -72,6 +73,7 @@ pub(super) use ops_remaining_tool_calls::RemainingToolCallsOperation;
7273
pub(super) use ops_remaining_tool_calls::UNCLAIMED_TOOL_ERROR;
7374
pub(crate) use ops_retry::is_retry_failure_message;
7475
pub(super) use ops_retry::RetryOperation;
76+
pub(super) use ops_rolling_memory::RollingMemoryOperation;
7577
pub(super) use ops_skills::{GooseSkillSource, NO_SKILLS_HELP};
7678
pub(super) use ops_status::StatusOperation;
7779
pub(super) use ops_stop_hook::{StopHookOperation, DEFAULT_BLOCK_CAP};

‎crates/goose/src/agents/state_machine/ops_compaction.rs‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Modified by Jonathan Mohrbacher, 2026: compaction failure messages are recognisable as turn errors.
1+
// 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.
22
//! Compacts conversation history when it is too large for the configured context window.
33
44
use std::sync::Arc;
@@ -193,16 +193,21 @@ impl Operation<Session, GooseEffect> for CompactionOperation {
193193
if context_errors > MAX_CONTEXT_ERROR_COMPACTIONS {
194194
return not_applicable();
195195
}
196-
} else if proactive_compaction_tokens(
197-
session,
198-
conversation,
199-
self.context_limit,
200-
self.threshold,
201-
)
202-
.await?
203-
.is_none()
204-
{
205-
return not_applicable();
196+
} else {
197+
if crate::context_mgmt::rolling::is_on(session) {
198+
return not_applicable();
199+
}
200+
if proactive_compaction_tokens(
201+
session,
202+
conversation,
203+
self.context_limit,
204+
self.threshold,
205+
)
206+
.await?
207+
.is_none()
208+
{
209+
return not_applicable();
210+
}
206211
}
207212

208213
let conversation_with_hidden_error;

0 commit comments

Comments
 (0)