Skip to content

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

Rust

keep mandatory thinking enabled for auxiliary summaries (#3556)

Sebastian Müller0ee10e11733a
diff --git a/crates/pa-core/src/session_engine/branch_summarization.rs b/crates/pa-core/src/session_engine/branch_summarization.rs
index 642edab5b4..3b4852e34f 100644
--- a/crates/pa-core/src/session_engine/branch_summarization.rs
+++ b/crates/pa-core/src/session_engine/branch_summarization.rs
@@ -452,13 +452,14 @@ pub async fn generate_branch_summary(
.collect(),
tools: None,
};
- let stream_options =
+ let mut stream_options =
pa_ai::types::SimpleStreamOptions::from_base(pa_ai::types::StreamOptions {
max_tokens: Some(BRANCH_SUMMARY_MAX_TOKENS),
api_key,
headers: summary_headers.map(|headers| headers.into_iter().collect()),
..Default::default()
});
+ stream_options.reasoning = pa_types::ai::minimum_reasoning(model);
let response = match pa_ai::complete_simple(model, &context, Some(stream_options)).await {
Ok(response) => response,
Err(error) => {
diff --git a/crates/pa-core/src/session_engine/compaction_exec.rs b/crates/pa-core/src/session_engine/compaction_exec.rs
index 255c17093d..1955eedb9e 100644
--- a/crates/pa-core/src/session_engine/compaction_exec.rs
+++ b/crates/pa-core/src/session_engine/compaction_exec.rs
@@ -165,11 +165,7 @@ pub async fn complete_summary_call(
headers: headers.map(|headers| headers.into_iter().collect()),
..Default::default()
});
- // Keep the provider default unless the model explicitly requires thinking.
- // Omitted reasoning disables thinking on toggle-based provider routes.
- let minimum = pa_types::ai::clamp_thinking_level(model, pa_types::ai::ModelThinkingLevel::Off);
- stream_options.reasoning =
- (minimum != pa_types::ai::ModelThinkingLevel::Off).then_some(minimum);
+ stream_options.reasoning = pa_types::ai::minimum_reasoning(model);
let assistant = match on_delta {
None => pa_ai::complete_simple(model, &context, Some(stream_options)).await?,
Some(on_delta) => {
diff --git a/crates/pa-core/src/session_engine/refine.rs b/crates/pa-core/src/session_engine/refine.rs
index 20d6a856e0..902bba6adf 100644
--- a/crates/pa-core/src/session_engine/refine.rs
+++ b/crates/pa-core/src/session_engine/refine.rs
@@ -625,11 +625,12 @@ pub fn default_refiner_call(api_key: Option<String>) -> crate::refinement::execu
})],
tools: None,
};
- let stream_options =
+ let mut stream_options =
pa_ai::types::SimpleStreamOptions::from_base(pa_ai::types::StreamOptions {
api_key,
..Default::default()
});
+ stream_options.reasoning = pa_types::ai::minimum_reasoning(&model);
Ok(pa_ai::complete_simple(&model, &context, Some(stream_options)).await?)
})
})
diff --git a/crates/pa-core/tests/compaction_transport.rs b/crates/pa-core/tests/compaction_transport.rs
index 026fb657f4..9efa4aac07 100644
--- a/crates/pa-core/tests/compaction_transport.rs
+++ b/crates/pa-core/tests/compaction_transport.rs
@@ -1,7 +1,12 @@
-//! Synthetic-provider regressions for summary request controls and cancellation.
+//! Synthetic-provider regressions for summary and refinement request controls and cancellation.
use std::time::Duration;
+use pa_core::session_engine::branch_summarization::{
+ generate_branch_summary, GenerateBranchSummaryOptions, DEFAULT_BRANCH_RESERVE_TOKENS,
+};
use pa_core::session_engine::compaction_exec::complete_summary_call;
+use pa_core::session_engine::refine::default_refiner_call;
+use pa_types::session::{AgentMessage, EntryBase, FileEntry};
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
@@ -175,3 +180,56 @@ async fn summary_preserves_unspecified_reasoning_when_off_is_supported() {
assert!(server.await.unwrap());
}
}
+
+#[tokio::test]
+async fn branch_summary_respects_mandatory_thinking() {
+ let (model, request, server) = mock_summary(Reply::Complete).await;
+ let entries = [FileEntry::Message {
+ message: AgentMessage::User(pa_types::ai::UserMessage {
+ content: pa_types::ai::UserContent::Text("explored a side branch".to_string()),
+ timestamp: 0,
+ rest: serde_json::Map::default(),
+ }),
+ base: EntryBase {
+ id: Some("u1".to_string()),
+ parent_id: None,
+ timestamp: Some("2024-01-01T00:00:00.000Z".to_string()),
+ rest: serde_json::Map::default(),
+ },
+ }];
+ let result = generate_branch_summary(
+ &entries,
+ GenerateBranchSummaryOptions {
+ model: &model,
+ api_key: Some("synthetic-key".into()),
+ custom_instructions: None,
+ replace_instructions: false,
+ reserve_tokens: DEFAULT_BRANCH_RESERVE_TOKENS,
+ auxiliary: None,
+ },
+ )
+ .await;
+ assert_eq!(result.error, None, "branch summary failed: {result:?}");
+ assert!(result
+ .summary
+ .as_deref()
+ .unwrap_or_default()
+ .contains("summary"));
+ assert_eq!(request.await.unwrap()["enable_thinking"], json!(true));
+ assert!(server.await.unwrap());
+}
+
+#[tokio::test]
+async fn refiner_call_respects_mandatory_thinking() {
+ let (model, request, server) = mock_summary(Reply::Complete).await;
+ let reply =
+ default_refiner_call(Some("synthetic-key".into()))(model, "system", "prompt".into())
+ .await
+ .unwrap();
+ assert!(matches!(
+ reply.content.as_slice(),
+ [pa_types::ai::AssistantContentBlock::Text(text)] if text.text == "summary"
+ ));
+ assert_eq!(request.await.unwrap()["enable_thinking"], json!(true));
+ assert!(server.await.unwrap());
+}
diff --git a/crates/pa-types/src/ai/mod.rs b/crates/pa-types/src/ai/mod.rs
index 15439fe760..2bdaa04f54 100644
--- a/crates/pa-types/src/ai/mod.rs
+++ b/crates/pa-types/src/ai/mod.rs
@@ -6,9 +6,9 @@
pub mod thinking_levels;
pub use thinking_levels::{
- clamp_thinking_level, get_supported_thinking_levels, models_are_equal, supports_thinking,
- thinking_level_from_str, thinking_level_index, thinking_level_map, EXTENDED_THINKING_LEVELS,
- SUPPORTED_THINKING_LEVELS,
+ clamp_thinking_level, get_supported_thinking_levels, minimum_reasoning, models_are_equal,
+ supports_thinking, thinking_level_from_str, thinking_level_index, thinking_level_map,
+ EXTENDED_THINKING_LEVELS, SUPPORTED_THINKING_LEVELS,
};
use serde::{Deserialize, Serialize};
diff --git a/crates/pa-types/src/ai/thinking_levels.rs b/crates/pa-types/src/ai/thinking_levels.rs
index e074c953f7..2718d6fde3 100644
--- a/crates/pa-types/src/ai/thinking_levels.rs
+++ b/crates/pa-types/src/ai/thinking_levels.rs
@@ -93,6 +93,16 @@ pub fn clamp_thinking_level(model: &Model, level: ModelThinkingLevel) -> ModelTh
.unwrap_or(ModelThinkingLevel::Off)
}
+/// The weakest reasoning a request may send: `None` (the provider default)
+/// when the model can run with thinking off, else its lowest supported level.
+/// Toggle-based routes read omitted reasoning as "thinking off", which
+/// mandatory-thinking models reject.
+#[must_use]
+pub fn minimum_reasoning(model: &Model) -> Option<ModelThinkingLevel> {
+ let minimum = clamp_thinking_level(model, ModelThinkingLevel::Off);
+ (minimum != ModelThinkingLevel::Off).then_some(minimum)
+}
+
/// Identity compare (`modelsAreEqual`): provider plus id.
#[must_use]
pub fn models_are_equal(a: Option<&Model>, b: Option<&Model>) -> bool {
diff --git a/scripts/review_minimum_reasoning_parity.py b/scripts/review_minimum_reasoning_parity.py
new file mode 100644
index 0000000000..d88bf09004
--- /dev/null
+++ b/scripts/review_minimum_reasoning_parity.py
@@ -0,0 +1,270 @@
+#!/usr/bin/env python3
+"""Capture mandatory-thinking summary/refiner requests from real TS/Rust binaries.
+
+The pinned TS v0.9.8 release and the current Rust binary run identical Python
+cells through their offered REPL tool. Only auxiliary request thinking controls
+are compared, recording TS summary thinking-off as the intended correction:
+prompt wording, token budgets, and whole UI/frame parity are not
+claimed. Branch summary uses an owned daemon and its real navigate_tree command.
+All providers, homes, sessions, and subprocesses belong to this fixture.
+"""
+import argparse
+import http.server
+import json
+import os
+from pathlib import Path
+import sys
+import socket
+import subprocess
+import time
+import tempfile
+import threading
+
+from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256
+from review_restore_notice_parity import invoke, probe_from
+from review_draft_disconnect_parity import stop
+
+MARKER = 'MINIMUM_REASONING_RESULT='
+
+
+class Server(http.server.ThreadingHTTPServer):
+ daemon_threads = True
+
+ def __init__(self, scenario):
+ super().__init__(('127.0.0.1', 0), Handler)
+ self.scenario = scenario
+ self.requests = []
+ self.main_requests = 0
+ self.tool_name = None
+ self.error = None
+
+
+class Handler(http.server.BaseHTTPRequestHandler):
+ def log_message(self, *_args):
+ pass
+
+ def do_POST(self):
+ if self.path != '/v1/chat/completions':
+ self.send_error(404)
+ return
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ auxiliary = not body.get('tools')
+ self.server.requests.append({'auxiliary': auxiliary, 'body': body})
+ if len(self.server.requests) > 12:
+ self.server.error = 'request limit exceeded'
+ self.send_error(422, self.server.error)
+ return
+ if auxiliary:
+ content = ('{"summary":"No durable change justified","rationale":"Fixture only",'
+ '"expectedOutcome":"No change","edits":[]}'
+ if self.server.scenario == 'refine' else
+ '## Goal\nVerify auxiliary thinking controls.\n## Progress\nSeed fixture complete.')
+ delta, finish = {'content': content}, 'stop'
+ else:
+ self.server.main_requests += 1
+ number = self.server.main_requests
+ if number == 1 or self.server.scenario == 'branch':
+ # Enough history for a real summary after a second user turn.
+ delta, finish = {'content': 'Seed observation. ' * 300}, 'stop'
+ elif number == 2:
+ offered = {tool.get('function', {}).get('name') for tool in body.get('tools', [])}
+ name = next((name for name in ('python_repl', 'ipython') if name in offered), None)
+ if name is None:
+ self.server.error = 'no supported REPL tool offered'
+ self.send_error(422, self.server.error)
+ return
+ self.server.tool_name = name
+ scenario = self.server.scenario
+ code = (f'import {scenario}, json\n'
+ f'result = await {scenario}.run("Verify mandatory thinking")\n'
+ f'print({MARKER!r} + json.dumps(result))')
+ delta = {'tool_calls': [{'index': 0, 'id': 'call_schedule', 'type': 'function',
+ 'function': {'name': name, 'arguments': json.dumps({'code': code})}}]}
+ finish = 'tool_calls'
+ else:
+ delta, finish = {'content': 'Fixture complete.'}, 'stop'
+ def chunk(value, reason=None):
+ return {'id': 'minimum-reasoning', 'object': 'chat.completion.chunk', 'created': 1,
+ 'model': 'mandatory-fixture', 'choices': [{'index': 0, 'delta': value,
+ 'finish_reason': reason}]}
+ wire = ''.join('data: ' + json.dumps(item) + '\n\n' for item in (
+ chunk({'role': 'assistant', **delta}), chunk({}, finish))) + 'data: [DONE]\n\n'
+ self.send_response(200)
+ self.send_header('Content-Type', 'text/event-stream')
+ self.send_header('Content-Length', str(len(wire.encode())))
+ self.end_headers()
+ self.wfile.write(wire.encode())
+
+
+def summarize_branch(binary, root, cwd, env, session_file, observation):
+ entries = [json.loads(line) for line in session_file.read_text().splitlines()]
+ target = next(row['id'] for row in entries
+ if row.get('type') == 'message' and row.get('message', {}).get('role') == 'assistant')
+ path = root / 'daemon.sock'
+ with (root / 'daemon.log').open('wb') as log:
+ process = subprocess.Popen([str(binary), '--mode', 'daemon', '--daemon-socket', str(path)],
+ cwd=cwd, env=env, stdout=log, stderr=log, start_new_session=True)
+ connection = None
+ try:
+ deadline = time.monotonic() + 35
+ while time.monotonic() < deadline:
+ assert process.poll() is None, 'owned daemon exited before socket readiness'
+ try:
+ connection = socket.socket(socket.AF_UNIX)
+ connection.settimeout(60)
+ connection.connect(str(path))
+ break
+ except (FileNotFoundError, ConnectionRefusedError):
+ connection.close()
+ connection = None
+ threading.Event().wait(0.05)
+ assert connection is not None, 'owned daemon socket never became ready'
+ with connection.makefile('rb') as reader:
+ hello = json.loads(reader.readline())
+ assert hello.get('type') == 'daemon_hello', hello
+ observation['daemon_hello'] = hello
+ def command(identifier, payload):
+ connection.sendall((json.dumps({'type': 'command', 'id': identifier,
+ 'protocol': hello['protocol'], 'command': payload}) + '\n').encode())
+ deadline = time.monotonic() + 60
+ while time.monotonic() < deadline:
+ line = reader.readline()
+ assert line, 'owned daemon closed before response'
+ row = json.loads(line)
+ observation.setdefault('daemon_wire', []).append(row)
+ if row.get('type') == 'response' and row.get('id') == identifier:
+ assert row.get('success') is True, row
+ return row
+ raise TimeoutError('no response for ' + identifier)
+ created = command('create', {'type': 'create', 'sessionPath': str(session_file),
+ 'config': {'cwd': str(cwd), 'sessionDir': str(session_file.parent)}})
+ active = created['data'].get('id') or created['data'].get('sessionId')
+ assert active, created
+ moved = command('branch', {'type': 'navigate_tree', 'activeSessionId': active,
+ 'targetId': target, 'summarize': True,
+ 'customInstructions': 'Verify mandatory thinking'})
+ assert moved.get('data', {}).get('cancelled') is not True, moved
+ finally:
+ if connection is not None:
+ connection.close()
+ stop(process)
+ observation['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')
+
+
+def run_case(binary, label, scenario, root, observation):
+ for name in ('home', 'agent', 'sessions', 'work', 'tmp'):
+ (root / name).mkdir(parents=True)
+ agent, sessions, cwd = root / 'agent', root / 'sessions', root / 'work'
+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'LC_ALL', 'TZ',
+ 'PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON') if key in os.environ}
+ library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'
+ paths = sorted(str(path) for path in library.glob('*/src') if path.is_dir())
+ for skill in ('compact', 'refine'):
+ assert (library / skill / 'src' / skill / '__init__.py').is_file(), skill + ' skill missing'
+ env.update(HOME=str(root / 'home'), TMPDIR=str(root / 'tmp'), DO_NOT_TRACK='1',
+ PI_OFFLINE='1', PI_CODING_AGENT_DIR=str(agent),
+ PRIME_AGENT_CODING_AGENT_DIR=str(agent), PI_SESSION_DIR=str(sessions),
+ PRIME_AGENT_SESSION_DIR=str(sessions), XDG_CONFIG_HOME=str(root / 'config'),
+ XDG_CACHE_HOME=str(root / 'cache'), XDG_DATA_HOME=str(root / 'data'),
+ PYTHONPATH=os.pathsep.join(paths))
+ if label == 'ts':
+ env['PI_PACKAGE_DIR'] = os.environ['PI_PACKAGE_DIR']
+ server = Server(scenario)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ (agent / 'models.json').write_text(json.dumps({'providers': {'fixture': {
+ 'api': 'openai-completions', 'apiKey': 'fixture-only',
+ # Provider-level compat is supported by both loaders. TS also merges
+ # model-level compat; Rust's existing custom loader ignores that field.
+ # Keep this fixture on their common configuration surface and require
+ # the exact zai wire toggle, without accepting another adapter's format.
+ 'compat': {'thinkingFormat': 'zai'},
+ 'baseUrl': 'http://127.0.0.1:%s/v1' % server.server_address[1],
+ 'models': [{'id': 'mandatory-fixture', 'name': 'Mandatory thinking fixture',
+ 'reasoning': True, 'input': ['text'], 'contextWindow': 128000,
+ 'maxTokens': 8192,
+ 'thinkingLevelMap': {'off': None, 'minimal': None, 'low': 'low',
+ 'medium': None, 'high': 'high', 'xhigh': None, 'max': 'max'}}]}}}))
+ (agent / 'settings.json').write_text(json.dumps({
+ 'defaultProvider': 'fixture', 'defaultModel': 'mandatory-fixture',
+ 'prewarmPythonKernel': False, 'compaction': {'enabled': False, 'keepRecentTokens': 100,
+ 'reserveTokens': 1024},
+ 'autoRefine': {'enabled': False}}))
+ command = [str(binary), '--mode', 'json', '--provider', 'fixture', '--model',
+ 'mandatory-fixture', '--thinking', 'low', '--session-dir', str(sessions),
+ 'Seed the fixture.', 'Schedule the requested auxiliary operation.']
+ try:
+ observation['version'] = invoke([str(binary), '--version'], cwd, env)
+ observation['process'] = invoke(command, cwd, env)
+ assert server.error is None, server.error
+ bodies = [row['body'] for row in server.requests]
+ if scenario == 'branch':
+ session_files = list(sessions.rglob('*.jsonl'))
+ assert len(session_files) == 1, session_files
+ summarize_branch(binary, root, cwd, env, session_files[0], observation)
+ scheduled = {'scheduled': True}
+ else:
+ scheduled = probe_from(bodies, MARKER)
+ observation['scheduled'] = scheduled
+ assert scheduled.get('scheduled') is True, scheduled
+ auxiliary = [row['body'] for row in server.requests if row['auxiliary']]
+ assert auxiliary, 'scheduled operation made no auxiliary provider request'
+ controls = [{key: body[key] for key in ('enable_thinking', 'thinking', 'reasoning_effort',
+ 'reasoning', 'chat_template_kwargs') if key in body} for body in auxiliary]
+ expected = {'enable_thinking': label == 'rust' or scenario == 'refine'}
+ assert all(control == expected for control in controls), {'expected': expected, 'actual': controls}
+ # A scheduled cell alone is insufficient: check the persisted operation result.
+ entries = [json.loads(line) for path in sessions.rglob('*.jsonl')
+ for line in path.read_text().splitlines() if line.strip()]
+ outcomes = [entry for entry in entries if
+ (scenario == 'compact' and entry.get('type') == 'compaction') or
+ (scenario == 'refine' and entry.get('customType') == 'refinement_outcome') or
+ (scenario == 'branch' and entry.get('type') == 'branch_summary')]
+ assert outcomes, 'no durable completed ' + scenario + ' outcome'
+ observation.update(controls=controls, outcome_count=len(outcomes), tool_name=server.tool_name)
+ return {'scheduled': scheduled['scheduled'], 'completed': bool(outcomes)}
+ finally:
+ observation['requests'] = server.requests
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--receipt', type=Path, required=True)
+ args = parser.parse_args()
+ result = {'verified': False, 'runs': {},
+ 'scope': 'Compaction, branch summary, and refinement auxiliary thinking controls; no frame parity claim.',
+ 'intended_difference': 'TS v0.9.8 compaction and branch summary requests disable zai thinking; Rust enables mandatory thinking. Refinement enables thinking in both.',
+ 'fixture_compat_scope': 'Provider-level zai compat used identically by both custom-model loaders; model-level compat is not relied on.',
+ 'comparison': 'Both schedule and persist completed outcomes. Every captured auxiliary request must match the exact expected control; request counts and full bodies remain in runs.'}
+ try:
+ assert sys.platform == 'linux', 'requires Linux hosted CI and pinned Linux TS binary'
+ archive_hash = sha256(os.environ['PA_TS_ARCHIVE'])
+ assert archive_hash == TS_ARCHIVE_SHA256, 'TS archive hash mismatch'
+ result['ts_release_archive_sha256'] = archive_hash
+ binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()
+ for label in ('ts', 'rust')}
+ result['binaries'] = {label: {'path': str(path), 'sha256': sha256(path)}
+ for label, path in binaries.items()}
+ with tempfile.TemporaryDirectory(prefix='minimum-reasoning-parity-') as temp:
+ for scenario in ('compact', 'branch', 'refine'):
+ results = {}
+ for label, binary in binaries.items():
+ observation = {}
+ result['runs'][scenario + '_' + label] = observation
+ results[label] = run_case(binary, label, scenario,
+ Path(temp) / scenario / label, observation)
+ assert results['ts'] == results['rust'], results
+ result['verified'] = True
+ except Exception as error:
+ result['error'] = str(error)
+ raise
+ finally:
+ args.receipt.parent.mkdir(parents=True, exist_ok=True)
+ args.receipt.write_text(json.dumps(result, indent=2) + '\n')
+
+
+if __name__ == '__main__':
+ main()