Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(agent): halt repeat loops that are not back to back (#6275)

M3gA-Minde5fa559c1424
diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.md
index 78a36bdb8e..a55ff0613e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/README.md
+++ b/crates/openhuman-core/src/agent/tinyagents/README.md
@@ -29,7 +29,7 @@ The **adapter seam** between OpenHuman and the vendored [`tinyagents`](../../../
| `replay/` | Read-only agent-run replay/status RPC (`mod.rs`, `ops.rs`, `schemas.rs`): three `agent`-namespace controllers over `journal.rs`. |
| `journal.rs` | `TurnJournal` and `FileStatusStore`: a crate `StoreEventJournal` over a JSONL append store plus a `HarnessStatusStore` writer under `{workspace}/tinyagents_store`. Attached alongside the live `observability` bridge as an independent `EventSink` subscriber, wrapped in `RedactingSink`; best-effort and non-fatal. |
| `reaper.rs` | `reap_orphaned_runs`: startup sweep that marks non-terminal runs `Cancelled` in the durable status store. The only writer over the status seam that `replay/` reads. |
-| `middleware.rs` + `middleware/` | The named OpenHuman middleware stack. `turn_context.rs`: `TurnContextMiddleware` (bundles config and installs the enabled hooks), `TranscriptSnapshotMiddleware`/`TranscriptSnapshotSink`, `HandoffConfig`/`HandoffMiddleware` (oversized sub-agent results stashed for `extract_from_result`). `prompt_cache.rs`: `PromptCacheSegmentMiddleware`. `tool_output.rs`: `ToolOutputMiddleware` (per-result byte cap and optional payload summarizer). `approval.rs`: `ApprovalSecurityMiddleware`. `cli_rpc_only.rs`: `CliRpcOnlyMiddleware`. `tool_policy.rs`: the `ToolPolicyMiddleware` struct and impl (records blocks into `crate::tools::registry::denials`). `tool_outcome_capture.rs`: `ToolOutcomeCaptureMiddleware`. `embedder_hooks.rs`: `EmbedderToolHooksMiddleware`. `arg_recovery.rs`: `ArgRecoveryMiddleware`. `memory_protocol.rs`: `MemoryProtocolMiddleware`. `cost_budget.rs`: `CostBudgetMiddleware`. `repeated_failure.rs`: `RepeatedToolFailureMiddleware`. `loop_guards.rs`: `TerminalInferenceFailure`. `repeat_progress.rs`: `RepeatProgressMiddleware`. `message_trim.rs`: `ImageAwareMessageTrimMiddleware`. `final_call_wrap_up.rs`: `FinalCallWrapUpMiddleware`. `artifact_index_toc.rs`: `ArtifactIndexTocMiddleware` (issue #6014). `credential_scrub.rs`: `CredentialScrubMiddleware` (issue #4453). |
+| `middleware.rs` + `middleware/` | The named OpenHuman middleware stack. `turn_context.rs`: `TurnContextMiddleware` (bundles config and installs the enabled hooks), `TranscriptSnapshotMiddleware`/`TranscriptSnapshotSink`, `HandoffConfig`/`HandoffMiddleware` (oversized sub-agent results stashed for `extract_from_result`). `prompt_cache.rs`: `PromptCacheSegmentMiddleware`. `tool_output.rs`: `ToolOutputMiddleware` (per-result byte cap and optional payload summarizer). `approval.rs`: `ApprovalSecurityMiddleware`. `cli_rpc_only.rs`: `CliRpcOnlyMiddleware`. `tool_policy.rs`: the `ToolPolicyMiddleware` struct and impl (records blocks into `crate::tools::registry::denials`). `tool_outcome_capture.rs`: `ToolOutcomeCaptureMiddleware`. `embedder_hooks.rs`: `EmbedderToolHooksMiddleware`. `arg_recovery.rs`: `ArgRecoveryMiddleware`. `memory_protocol.rs`: `MemoryProtocolMiddleware`. `cost_budget.rs`: `CostBudgetMiddleware`. `repeated_failure.rs`: `RepeatedToolFailureMiddleware`. `loop_guards.rs`: `TerminalInferenceFailure`. `repeat_progress.rs`: `RepeatProgressMiddleware` (adjacent-repeat streaks plus a run-wide `(call, result)` recurrence ledger) and `RepeatEvictionObserver` (registered last; resets the ledger when compaction evicts a recorded result, #6275). `message_trim.rs`: `ImageAwareMessageTrimMiddleware`. `final_call_wrap_up.rs`: `FinalCallWrapUpMiddleware`. `artifact_index_toc.rs`: `ArtifactIndexTocMiddleware` (issue #6014). `credential_scrub.rs`: `CredentialScrubMiddleware` (issue #4453). |
| `model.rs` | Helpers and wrappers over native crate `ChatModel` values: message/response translation, usage merging, stream-delta forwarding, `MaxTokensModel`, `ProfileOverrideModel`, `RouteRecordingModel`. |
| `convert.rs` | `spec_to_schema`: OpenHuman `ToolSpec` → crate `ToolSchema`. Message conversion lives in `crate::agent::message_convert`. |
| `tools.rs` | `SharedToolAdapter` / `ToolAdapter`: wrap `Arc<dyn crate::tools::Tool>` as a crate `Tool`; `EarlyExitHook` for `ask_user_clarification`-style pauses; `execute_openhuman_tool`. |
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
index 9bb0a2f150..b70a8aa3a4 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
@@ -292,11 +292,14 @@ pub(super) fn assemble_turn_harness(
// guard halts on identical successful `(tool, args)` batches / identical
// outputs, sharing the same halt-summary slot + steering handle. Polling tools
// (`wait_subagent`) stay exempt.
- if let Some(handle) = &handle {
- harness.push_middleware(Arc::new(middleware::RepeatProgressMiddleware::new(
+ let repeat_progress = handle.as_ref().map(|handle| {
+ Arc::new(middleware::RepeatProgressMiddleware::new(
handle.clone(),
halt_summary.clone(),
- )));
+ ))
+ });
+ if let Some(mw) = &repeat_progress {
+ harness.push_middleware(mw.clone());
}
// Policy-driven stop hooks (budget cap, thread-goal budget, ad-hoc iteration
@@ -691,6 +694,14 @@ pub(super) fn assemble_turn_harness(
)));
}
+ // Registered last so its `before_model` sees the request after every
+ // reduction step above (compression, microcompact, trim) has run. A tool
+ // result they evicted is no longer a repeat the model can see, so the
+ // repeat-progress recurrence ledger restarts (#6275).
+ if let Some(mw) = &repeat_progress {
+ harness.push_middleware(Arc::new(mw.eviction_observer()));
+ }
+
AssembledTurnHarness {
harness,
cursor,
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_progress.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_progress.rs
index fcbe059306..06b344d2b2 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_progress.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_progress.rs
@@ -1,19 +1,26 @@
//! [`RepeatProgressMiddleware`]: host adapter for the crate successful-repeat
//! tracker — halts identical-output / identical-call loops that succeed but
-//! make no progress (#4088 / #4095).
+//! make no progress (#4088 / #4095), including loops whose repeats are not
+//! back to back (#6275).
+
+use std::collections::{HashMap, HashSet};
+use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use tinyagents_harness::context::RunContext;
use tinyagents_harness::error::Result as TaResult;
use tinyagents_harness::middleware::Middleware;
-use tinyagents_harness::no_progress::{SuccessfulRepeat, SuccessfulRepeatTracker};
+use tinyagents_harness::no_progress::{
+ fingerprint_arguments, SuccessfulRepeat, SuccessfulRepeatTracker,
+};
use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};
use tinyagents_harness::tool::ToolResult as TaToolResult;
-use tinyinference::message::ContentBlock;
-use tinyinference::model::ModelResponse;
+use tinyinference::message::{ContentBlock, Message};
+use tinyinference::model::{ModelRequest, ModelResponse};
use super::loop_guards::is_repeat_call_exempt;
+use crate::agent::context::CLEARED_PLACEHOLDER;
/// Extract the assistant's visible text (concatenated [`ContentBlock::Text`]
/// blocks) from a model response message, for the repeat-output signature.
@@ -44,6 +51,40 @@ struct PendingCallBatch {
all_ok: bool,
/// `true` when every call in the batch is a polling/wait exemption.
exempt: bool,
+ /// `call_id` → per-call `(tool, argument fingerprint)` signature for the
+ /// recurrence ledger. Polling/wait calls are left out.
+ call_sigs: HashMap<String, String>,
+ /// `true` once a result in this batch has already halted the run, so the
+ /// batch does not pause it a second time.
+ halted: bool,
+}
+
+/// Tracker state shared between [`RepeatProgressMiddleware`] and its
+/// [`RepeatEvictionObserver`].
+#[derive(Default)]
+struct RepeatState {
+ tracker: SuccessfulRepeatTracker,
+ /// `call_id`s of the results fed to the recurrence ledger since its last reset.
+ recorded: Mutex<HashSet<String>>,
+ /// Recorded results still verbatim in the current request before any
+ /// reduction step ran; compared against the final request by the observer.
+ visible_before_reduction: Mutex<HashSet<String>>,
+}
+
+/// The `ids` whose tool result is still in `request` with its body intact.
+fn visible_tool_results(request: &ModelRequest, ids: &HashSet<String>) -> HashSet<String> {
+ request
+ .messages
+ .iter()
+ .filter_map(|message| match message {
+ Message::Tool(tool)
+ if ids.contains(&tool.tool_call_id) && message.text() != CLEARED_PLACEHOLDER =>
+ {
+ Some(tool.tool_call_id.clone())
+ }
+ _ => None,
+ })
+ .collect()
}
/// Host adapter for the crate's successful-repeat tracker (#4088 / #4095).
@@ -59,19 +100,29 @@ struct PendingCallBatch {
/// on every call succeeding): halts when the `(tool, args)` batch alone repeats
/// [`DEFAULT_REPEAT_CALL_THRESHOLD`] times — catching successful no-op loops
/// that vary only their narration.
+/// - **Recurrence** (each successful `after_tool`, #6275): halts when one call
+/// returns the identical result [`DEFAULT_REPEAT_CALL_THRESHOLD`] times in the
+/// run, adjacent or not — catching a model cycling A, B, A, B through steps
+/// whose results it already has. The result is the content after the earlier
+/// `after_tool` layers (caps, summarizer), i.e. what the model saw, so a
+/// re-read whose output changed does not count. A result that compaction
+/// later evicts stops counting; see [`RepeatEvictionObserver`].
///
-/// Polling/wait tools ([`is_repeat_call_exempt`]) are exempt from both: their
-/// contract is to be re-invoked identically, so an all-poll batch resets the
-/// streaks instead of recording. On a trip it writes the legacy root-cause
+/// Polling/wait tools ([`is_repeat_call_exempt`]) are exempt from all three:
+/// their contract is to be re-invoked identically, so an all-poll batch resets
+/// the streaks instead of recording. On a trip it writes the legacy root-cause
/// summary into the shared [`HaltSummarySlot`](crate::agent::tinyagents::HaltSummarySlot) and pauses
/// the run through the shared steering handle — the same halt mechanism as the
/// repeated-failure breaker.
+///
+/// [`DEFAULT_REPEAT_OUTPUT_THRESHOLD`]: tinyagents_harness::no_progress::DEFAULT_REPEAT_OUTPUT_THRESHOLD
+/// [`DEFAULT_REPEAT_CALL_THRESHOLD`]: tinyagents_harness::no_progress::DEFAULT_REPEAT_CALL_THRESHOLD
pub(crate) struct RepeatProgressMiddleware {
handle: SteeringHandle,
halt_summary: crate::agent::tinyagents::HaltSummarySlot,
- tracker: SuccessfulRepeatTracker,
+ state: Arc<RepeatState>,
/// Batch bookkeeping bridging `after_model` → `after_tool` for the call guard.
- pending: std::sync::Mutex<Option<PendingCallBatch>>,
+ pending: Mutex<Option<PendingCallBatch>>,
}
impl RepeatProgressMiddleware {
@@ -82,8 +133,17 @@ impl RepeatProgressMiddleware {
Self {
handle,
halt_summary,
- tracker: SuccessfulRepeatTracker::default(),
- pending: std::sync::Mutex::new(None),
+ state: Arc::new(RepeatState::default()),
+ pending: Mutex::new(None),
+ }
+ }
+
+ /// The companion that resets the recurrence ledger when a recorded result is
+ /// evicted from context. It must be registered after every reduction
+ /// middleware, and this guard before them.
+ pub(crate) fn eviction_observer(&self) -> RepeatEvictionObserver {
+ RepeatEvictionObserver {
+ state: Arc::clone(&self.state),
}
}
@@ -104,6 +164,24 @@ impl Middleware<()> for RepeatProgressMiddleware {
"repeat_progress"
}
+ async fn before_model(
+ &self,
+ _ctx: &mut RunContext<()>,
+ _state: &(),
+ request: &mut ModelRequest,
+ ) -> TaResult<()> {
+ // Registered ahead of the reduction steps, so this is the request as the
+ // loop built it. The observer compares the same ids after they ran.
+ let visible = match self.state.recorded.lock() {
+ Ok(recorded) if !recorded.is_empty() => visible_tool_results(request, &recorded),
+ _ => HashSet::new(),
+ };
+ if let Ok(mut slot) = self.state.visible_before_reduction.lock() {
+ *slot = visible;
+ }
+ Ok(())
+ }
+
async fn after_model(
&self,
_ctx: &mut RunContext<()>,
@@ -140,10 +218,26 @@ impl Middleware<()> for RepeatProgressMiddleware {
assistant_visible_text(&response.message).trim(),
call_sig
);
+ // Per-call signatures for the recurrence ledger, keyed by `call_id` so
+ // each result can be matched to the arguments that produced it.
+ let call_sigs = tool_calls
+ .iter()
+ .filter(|call| !is_repeat_call_exempt(&call.name))
+ .map(|call| {
+ (
+ call.id.clone(),
+ format!(
+ "{}\u{1}{}",
+ call.name,
+ fingerprint_arguments(&call.arguments)
+ ),
+ )
+ })
+ .collect();
// Stage output with the crate tracker. Its halt verdict is intentionally
// deferred until the matching tool batch is confirmed successful.
- let _ = self.tracker.record_output(&output_sig, all_exempt);
+ let _ = self.state.tracker.record_output(&output_sig, all_exempt);
// Stage the batch for the repeat-CALL guard, evaluated once every result
// is back (gated on success) in `after_tool`.
@@ -153,6 +247,8 @@ impl Middleware<()> for RepeatProgressMiddleware {
remaining: tool_calls.len(),
all_ok: true,
exempt: all_exempt,
+ call_sigs,
+ halted: false,
});
}
Ok(())
@@ -164,35 +260,116 @@ impl Middleware<()> for RepeatProgressMiddleware {
_state: &(),
result: &mut TaToolResult,
) -> TaResult<()> {
- // Fold this result into the pending batch; only act once the batch is
- // complete so the call guard sees whole-batch success.
- let completed = {
+ // Fold this result into the pending batch; the call guard only acts once
+ // the batch is complete so it sees whole-batch success.
+ let (already_halted, recurrence, completed) = {
let Ok(mut pending) = self.pending.lock() else {
return Ok(());
};
let Some(batch) = pending.as_mut() else {
return Ok(());
};
+ let already_halted = batch.halted;
+ let mut recurrence = SuccessfulRepeat::Continue;
if result.error.is_some() {
batch.all_ok = false;
+ } else if let Some(sig) = batch.call_sigs.get(&result.call_id) {
+ recurrence = self.state.tracker.record_call_outcome(sig, &result.content);
+ if let Ok(mut recorded) = self.state.recorded.lock() {
+ recorded.insert(result.call_id.clone());
+ }
+ }
+ if matches!(recurrence, SuccessfulRepeat::Halt(_)) {
+ batch.halted = true;
}
batch.remaining = batch.remaining.saturating_sub(1);
- if batch.remaining == 0 {
+ let completed = if batch.remaining == 0 {
pending.take()
} else {
None
- }
+ };
+ (already_halted, recurrence, completed)
};
- let Some(batch) = completed else {
+ if already_halted {
+ // An earlier result in this batch paused the run; keep the streak
+ // accounting current without pausing again.
+ if let Some(batch) = completed {
+ let _ = self.state.tracker.record_call_batch(
+ &batch.call_sig,
+ batch.all_ok,
+ batch.exempt,
+ );
+ }
return Ok(());
- };
+ }
- if let SuccessfulRepeat::Halt(summary) =
- self.tracker
+ let batch_verdict = completed.map(|batch| {
+ self.state
+ .tracker
.record_call_batch(&batch.call_sig, batch.all_ok, batch.exempt)
- {
- tracing::warn!("[tinyagents::mw] crate successful-repeat tracker halted the run");
- self.halt(summary);
+ });
+ // When both fire on the same result, the batch summary wins: it is the
+ // more specific description of an adjacent repeat.
+ let summary = match (batch_verdict, recurrence) {
+ (Some(SuccessfulRepeat::Halt(summary)), _) => summary,
+ (_, SuccessfulRepeat::Halt(summary)) => summary,
+ _ => return Ok(()),
+ };
+ tracing::warn!(
+ tool = %result.name,
+ "[tinyagents::mw] crate successful-repeat tracker halted the run"
+ );
+ self.halt(summary);
+ Ok(())
+ }
+}
+
+/// Resets [`RepeatProgressMiddleware`]'s recurrence ledger when context
+/// reduction evicts a recorded tool result (#6275).
+///
+/// Compression, microcompact and trim rewrite only the outgoing request, never
+/// the loop's transcript, so the eviction is visible only inside the
+/// `before_model` chain. The guard snapshots which recorded results are intact
+/// before those steps; this observer, registered after them, checks the same
+/// ids in the final request. A result that was blanked or dropped is no longer
+/// in front of the model, so re-reading it is not a repeat the model can see,
+/// and the tracker restarts. Keyed on what disappeared rather than on which
+/// middleware removed it, so any reduction step is covered, and a dialect that
+/// never carries tool results as tool messages is never snapshotted.
+pub(crate) struct RepeatEvictionObserver {
+ state: Arc<RepeatState>,
+}
+
+#[async_trait]
+impl Middleware<()> for RepeatEvictionObserver {
+ fn name(&self) -> &str {
+ "repeat_progress_eviction"
+ }
+
+ async fn before_model(
+ &self,
+ _ctx: &mut RunContext<()>,
+ _state: &(),
+ request: &mut ModelRequest,
+ ) -> TaResult<()> {
+ let before = match self.state.visible_before_reduction.lock() {
+ Ok(mut slot) => std::mem::take(&mut *slot),
+ Err(_) => return Ok(()),
+ };
+ if before.is_empty() {
+ return Ok(());
+ }
+ let evicted = before.len() - visible_tool_results(request, &before).len();
+ if evicted == 0 {
+ return Ok(());
+ }
+ tracing::debug!(
+ evicted,
+ "[tinyagents::mw] repeat-progress ledger reset: recorded tool results left the context"
+ );
+ self.state.tracker.reset();
+ if let Ok(mut recorded) = self.state.recorded.lock() {
+ recorded.clear();
}
Ok(())
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs
index 5561136822..9ceeb2d061 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs
@@ -469,10 +469,10 @@ async fn successful_repeat_tracker_halt_maps_to_summary_and_pause() {
let mw = RepeatProgressMiddleware::new(handle.clone(), summary.clone());
for _ in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {
- run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), None).await;
+ run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), "ok", None).await;
assert_eq!(drain_pause_count(&handle), 0);
}
- run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), None).await;
+ run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), "ok", None).await;
assert_eq!(drain_pause_count(&handle), 1);
assert!(
@@ -493,12 +493,23 @@ async fn successful_repeat_tracker_resets_failed_and_exempt_batches() {
std::sync::Arc::new(std::sync::Mutex::new(None)),
);
- for _ in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {
- run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), None).await;
+ // Distinct outputs keep the run-wide recurrence ledger out of this test: it
+ // pins the adjacent-batch streak, which a failure resets.
+ for i in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {
+ let output = format!("before-{i}");
+ run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), &output, None).await;
}
- run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), Some("temporary failure")).await;
- for _ in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {
- run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), None).await;
+ run_successful_repeat_cycle(
+ &mw,
+ "lookup",
+ json!({"id": 1}),
+ "ok",
+ Some("temporary failure"),
+ )
+ .await;
+ for i in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {
+ let output = format!("after-{i}");
+ run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), &output, None).await;
}
assert_eq!(
drain_pause_count(&handle),
@@ -507,7 +518,8 @@ async fn successful_repeat_tracker_resets_failed_and_exempt_batches() {
);
for _ in 0..DEFAULT_REPEAT_OUTPUT_THRESHOLD + 1 {
- run_successful_repeat_cycle(&mw, "wait_subagent", json!({"task_id": "t"}), None).await;
+ run_successful_repeat_cycle(&mw, "wait_subagent", json!({"task_id": "t"}), "ok", None)
+ .await;
}
assert_eq!(
drain_pause_count(&handle),
@@ -516,6 +528,142 @@ async fn successful_repeat_tracker_resets_failed_and_exempt_batches() {
);
}
+// ── #6275: repeats that are not back to back ────────────────────────────
+
+/// One A, B round of two different successful calls, each returning the given
+/// output. The adjacent-batch streak restarts on every step of such a cycle.
+async fn run_alternating_round(mw: &RepeatProgressMiddleware, a_output: &str, b_output: &str) {
+ run_successful_repeat_cycle(mw, "use_skill", json!({"skill": "skills"}), a_output, None).await;
+ run_successful_repeat_cycle(
+ mw,
+ "use_skill",
+ json!({"skill": "skills", "tool": "skill_search"}),
+ b_output,
+ None,
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn alternating_identical_successful_calls_halt_on_recurrence() {
+ let handle = SteeringHandle::allow_all();
+ let summary = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let mw = RepeatProgressMiddleware::new(handle.clone(), summary.clone());
+
+ for _ in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {
+ run_alternating_round(&mw, "doc", "hits").await;
+ }
+ assert_eq!(drain_pause_count(&handle), 0);
+
+ run_successful_repeat_cycle(&mw, "use_skill", json!({"skill": "skills"}), "doc", None).await;
+ assert_eq!(
+ drain_pause_count(&handle),
+ 1,
+ "an alternating call returning the identical result for the third time must halt the run"
+ );
+ assert!(
+ summary
+ .lock()
+ .unwrap()
+ .as_deref()
+ .is_some_and(|text| text.contains("identical result")),
+ "the recurrence halt summary should reach the host turn result"
+ );
+}
+
+#[tokio::test]
+async fn alternating_calls_whose_output_changed_do_not_halt() {
+ let handle = SteeringHandle::allow_all();
+ let mw = RepeatProgressMiddleware::new(
+ handle.clone(),
+ std::sync::Arc::new(std::sync::Mutex::new(None)),
+ );
+ for i in 0..DEFAULT_REPEAT_CALL_THRESHOLD * 3 {
+ run_alternating_round(&mw, &format!("doc-{i}"), &format!("hits-{i}")).await;
+ }
+ assert_eq!(
+ drain_pause_count(&handle),
+ 0,
+ "a re-read with identical arguments whose output changed is progress, not a repeat"
+ );
+}
+
+#[tokio::test]
+async fn alternating_exempt_polling_calls_do_not_halt() {
+ let handle = SteeringHandle::allow_all();
+ let mw = RepeatProgressMiddleware::new(
+ handle.clone(),
+ std::sync::Arc::new(std::sync::Mutex::new(None)),
+ );
+ for i in 0..DEFAULT_REPEAT_CALL_THRESHOLD * 3 {
+ run_successful_repeat_cycle(
+ &mw,
+ "wait_subagent",
+ json!({"task_id": "t"}),
+ "still running",
+ None,
+ )
+ .await;
+ let output = format!("status-{i}");
+ run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), &output, None).await;
+ }
+ assert_eq!(
+ drain_pause_count(&handle),
+ 0,
+ "identical polling results must not feed the recurrence ledger"
+ );
+}
+
+#[tokio::test]
+async fn evicting_a_recorded_result_resets_the_recurrence_ledger() {
+ // What the last `before_model` sees for the recorded result `repeat-1`:
+ // untouched, blanked by microcompact, or dropped by compression / trim.
+ let cases: [(Vec<TaMessage>, usize, &str); 3] = [
+ (
+ vec![TaMessage::tool("repeat-1", "doc")],
+ 1,
+ "a result still in context keeps counting",
+ ),
+ (
+ vec![TaMessage::tool("repeat-1", CLEARED_PLACEHOLDER)],
+ 0,
+ "a result blanked by compaction must not count toward a repeat",
+ ),
+ (
+ vec![],
+ 0,
+ "a result dropped by compaction must not count toward a repeat",
+ ),
+ ];
+ for (compacted, expected_pauses, why) in cases {
+ let handle = SteeringHandle::allow_all();
+ let mw = RepeatProgressMiddleware::new(
+ handle.clone(),
+ std::sync::Arc::new(std::sync::Mutex::new(None)),
+ );
+ let observer = mw.eviction_observer();
+ for _ in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {
+ run_alternating_round(&mw, "doc", "hits").await;
+ }
+
+ // The next model call: the guard sees the request before the reduction
+ // steps run, the observer after them.
+ let mut request = ModelRequest::new(vec![TaMessage::tool("repeat-1", "doc")]);
+ mw.before_model(&mut ctx(), &(), &mut request)
+ .await
+ .unwrap();
+ let mut request = ModelRequest::new(compacted);
+ observer
+ .before_model(&mut ctx(), &(), &mut request)
+ .await
+ .unwrap();
+
+ run_successful_repeat_cycle(&mw, "use_skill", json!({"skill": "skills"}), "doc", None)
+ .await;
+ assert_eq!(drain_pause_count(&handle), expected_pauses, "{why}");
+ }
+}
+
// ── ApprovalSecurityMiddleware ──────────────────────────────────────────
#[test]
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
index 97920b1431..3c10facf24 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
@@ -314,13 +314,16 @@ async fn run_successful_repeat_cycle(
mw: &RepeatProgressMiddleware,
tool: &str,
args: serde_json::Value,
+ output: &str,
error: Option<&str>,
) {
let mut response = repeated_success_response(tool, args);
mw.after_model(&mut ctx(), &(), &mut response)
.await
.unwrap();
- let mut result = tool_result(tool, "ok");
+ let mut result = tool_result(tool, output);
+ // Answer the call `repeated_success_response` issued.
+ result.call_id = "repeat-1".into();
result.error = error.map(str::to_string);
mw.after_tool(&mut ctx(), &(), &mut result).await.unwrap();
}
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 44afb2e688..89256cc54e 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 44afb2e6884690a59eb43e268a09868a9852c410
+Subproject commit 89256cc54ed1ce94ea53d585587687b6c6b8d1cb