Repository navigation
loop prevention
How an always-on agent stops itself from getting stuck: per-turn pathology guards on model and tool calls, exponential-backoff breakers on background services, reliable completion delivery between subagents, process-level crash gating at boot, and REST / manual escape hatches when everything else fails.
A runaway loop is any cycle the system cannot exit on its own: a model call that repeats the same text forever, a tool call retried with the same failing arguments, a heartbeat or cron job that ticks into the void, a subagent completion that never reaches its parent (or reaches it twice), or a process that crashes and gets restarted into the same crash. This harness runs unattended (cron schedules, heartbeat wake-ups, subagent sweeps, long chat turns), so every loop must have a bound that the system itself enforces, not just a prompt asking the model to behave.
Two design rules run through every guard below:
- Degrade, never crash. Protection never takes the process down: background services stop, turns end gracefully, and the boot gate narrows the footprint to HTTP-only mode.
- Always leave a hatch. Every breaker has a documented manual reset (REST endpoint, state-file delete, or process restart).
Source of truth: agent/middlewares/tool_guardrails/core.py, agent/middlewares/iteration_budget/core.py, agent/middlewares/delegation_pressure/core.py, agent/middlewares/max_tokens_boost/core.py, agent/middlewares/output_repetition_guard/core.py, agent/wrapper/repetition_guard.py, agent/middlewares/heartbeat_staleness/core.py, agent/middlewares/subagent_completion_drain/core.py, agent/tools/subagent/announce/delivery.py, agent/tools/subagent/announce/idempotency.py, models/LLMs/provider_repetition_penalty.py, config/models_settings.py, runtime/process/periodic_backoff.py, runtime/process/crash_loop_breaker.py, skills/builtin/core/cron/scripts/base.py, skills/builtin/core/heartbeat/scripts/base.py, agent/tools/subagent/registry/sweeper.py, server/__main__.py, server/trigger/http/cron.py, server/trigger/__init__.py, server/trigger/channels/core.py, pub/func/message/overflow_clip.py.
| Loop altitude | What it looks like | Defense |
|---|---|---|
| Text death loop (one model call) | Same sentence / character run streamed forever | Per-family sampling penalty (frequency_penalty / presence_penalty) → OutputRepetitionGuard (worker) + RepetitionGuardWrapper (main-agent stream) |
| Tool pathology loop (one turn) | Same failing tool call, ping-pong pairs, argument churn |
ToolGuardrails: 5 pathologies → WARN → BLOCK → HALT, with recovery mode |
| Unbounded turn | Model calls never stop |
IterationBudget (180 main / 90 executor / 60 other workers; model calls only — tool results are free) |
| Truncation retry spiral | A max_tokens-truncated tool call executes as garbage → error → the model re-issues it, burning iterations |
MaxTokensBoostMiddleware: bounded in-middleware re-call (3 retries, capped boost, +0 budget) |
| Overflow retry spiral | An oversized context is rejected → compression fires → the compacted context still overflows → the provider errors again |
Summarization: no-LLM overflow tail clip first, then the existing overflow route, then forced recovery |
| Stuck turn | No progress for minutes (hung tool, wedged loop) |
HeartbeatStaleness watchdog → HeartbeatTimeoutError
|
| Background service loop | Heartbeat / sweeper / cron tick failing forever |
PeriodicBackoff (exhaustion = service stops) / cron degrade → auto-disable |
| Lost or duplicated completion | Subagent finished, but the parent never hears about it, or hears twice | Completion drain (inject-once) + announce retry ladder + idempotency keys |
| Crash-reboot loop | Process crashes at boot, supervisor restarts into the same crash |
CrashLoopBreaker → HTTP-only mode |
| Everything else | A breaker disabled a job or tripped the boot gate | Cron REST failure-state / reset-failures, state-file reset |
The defense is layered by altitude, so a failure that slips one layer lands in the next:
- Turn level: per-turn guards bound a single conversation turn (text, tool, iteration, staleness).
-
Recovery interlude: a
ToolGuardrailsBLOCK gets one managed retry window before escalating to HALT. - Background level: recurring services back off exponentially and stop after 5 consecutive failures.
- Process level: a crash-reboot loop trips a boot breaker that boots into a minimal HTTP-only mode.
- Operations: REST endpoints and documented manual resets.
Active on the main agent, worker agents, and background-review sub-agents. Every tool call record is appended to per-turn state (tool_guardrail_state in state_register_mem) before evaluation, so thresholds are self-inclusive: "after 2" means the current call is the 2nd, and the 5th identical no-progress call itself reaches np=5 and blocks. Escalation ladder: ALLOW → WARN (a nudge is appended to the transcript) → BLOCK (the call is rejected with an explanatory message) → HALT (the turn ends gracefully with a terminal message, same pattern as the iteration budget).
| Pathology | Signal | WARN after | BLOCK after | hard-stop mode |
|---|---|---|---|---|
| Exact-failure repetition | Same tool + same (hashed) args keeps failing | 2 | 5 | HALT at 5 |
| Same-tool failure storm | Same tool keeps failing, args may vary | 3 | 8 | HALT at 8 |
| Idempotent no-progress | Same idempotent tool (or idempotent action of a grouped tool) returning a result hash an earlier call of it already produced | 2 | 5 | HALT at 5 |
| Ping-pong | Unbroken A → B → A → B bouncing where both consecutive calls are stagnant | 4 | 6 | HALT at 6 |
| Argument churn | Same idempotent tool cycling argument variants whose result stays unchanged (stagnant) | 3 variants | 5 variants | HALT at 5 |
| Signature streak (status-blind) | Same tool + same argument hash repeated consecutively, regardless of result status (terminal uses 5) | 3 (terminal: 5) | that exact signature, after the 3-warning budget is spent | WARN up to 3 per turn, then the exact call is blocked for the rest of the turn; a signature change resets the streak |
| Result repetition (non-idempotent) | Same tool returns a byte-identical result on consecutive calls while the arguments change (probe1.py, probe2.py, …) |
3 | 6 | HALT at 6 |
Network-command failures are now bridged to tool errors: a non-zero curl/wget/git fetch/git clone raises ToolException, so handle_tool_error produces ToolMessage(status="error") and the exact-failure counter sees it. Local commands (pytest, compilers, scripts) keep their non-zero exit as normal text (status="success") so the agent can read the failure and iterate. web_fetch HTTP 4xx/5xx likewise raises. The signature streak catches the other blind spot: successful-looking repeats with identical arguments. It warns up to streak_max_warnings_per_turn times; once that budget is spent the exact tool+args signature is blocked for the rest of the turn, so a degenerate loop that keeps re-running one command cannot consume the whole iteration budget. The block is scoped to that signature — other arguments and tools stay available — and it bypasses recovery mode (a repetition block must not be released as a one-off retry).
One deliberate exemption: a read_file whose path is a test file (tests/ segment, test_*.py, *_test.py) is acceptance feedback, not probing. It neither advances the signature streak nor feeds the no-progress/pair paths, so an agent can re-read the expectation after a failed assertion. Only read_file is exempt; terminal/search and source-file reads keep the normal counting.
Result repetition covers the loop signature detection still misses: the arguments change every call while the output stays byte-identical. The SWE 20261103_203547 Sympy run is the canonical case — the agent wrote probe1.py through probe19.py, each printing the same prettyForm, and burned the 90-call budget without touching the library. The detector keeps a per-tool consecutive-result streak for NON-idempotent tools (idempotent tools already use the no-progress chain), warns once per tool at result_repetition_warn_after, and blocks the whole tool at result_repetition_block_after; like the signature block it bypasses recovery mode, and the block lasts for the rest of the turn. Other tools (including the write tools) remain available, so the agent can still apply the change it was circling.
A successful source edit releases the blocks: patch_file declares clears_guardrail_blocks in its own metadata, and ToolGuardrails drops every accumulated block, signature, result streak, and failure/no-progress counter (plus the call records) when such a call succeeds. The probes that tripped the guard were answered by the pre-edit file, so keeping the verification tools blocked would only prevent the agent from testing its new candidate. A scratch write_file (a new probeN.py) does NOT carry the flag, so it cannot re-open the loop it is part of.
Details that matter:
-
Recovery mode (
recovery_mode_enabled=Trueby default): the first BLOCK does not brick the turn. The turn enters recovery, and the precheck path releases the blocked tool so the retry is evaluated fresh. Each further BLOCK increments a violation counter; once the counter exceedsrecovery_max_violations(default 1), the action escalates to HALT. In effect: a managed retry window instead of an immediate wall. Setrecovery_mode_enabled=Falsefor strict no-recovery behavior, orhard_stop_enabled=Trueto turn every BLOCK threshold into HALT (see table). -
No progress means stagnation (
is_stagnant): a successful idempotent call is only no-progress when the same tool already produced this exact result hash earlier in the turn; a changed result is progress. A grouped tool may declareidempotent_actionsinstead of a whole-tool flag: only a call whoseactionargument is in that allowlist is hashed (TaskFlow hashescreate/plan/update_steps/resume;knowledgehashesread/list). The allowlist takes precedence over the scalar flag, and an unlisted or missing action is never treated as repeatable. Ping-pong pairs hash the two tool names of adjacent calls and accumulate only while both consecutive calls are stagnant. Any error, a changed (non-stagnant) result, or a successful non-idempotent (mutating) call zeroes every accumulated pair streak. A changed idempotent result likewise stops counting toward argument churn, and a successful non-idempotent call clears the argument-churn state entirely. - Guard state is strictly turn-scoped:
before_agentresets it, so a fresh turn starts clean.
Counts model calls per turn, one unit each. A tool-call pair costs exactly one unit: the model call that produced the calling AIMessage; its ToolMessage result is free. HumanMessage / SystemMessage / injected system reminders never charge on their own — only the next model call does. Main agent 180, the executor subagent 90, other worker agents 60 (base default 50). An exhausted model call returns a terminal AIMessage instead of calling the model, so a tool call already requested by the last budgeted AIMessage still runs and its pair stays intact. Internal completion-notification turns are exempt (they don't pay iterations). Counters (iteration_budget / iteration_budget_used) reset every turn.
Installed on the MAIN agent and never on a subagent (the child builder does not add it, and _active rejects :subagent:/:swarm: sessions). It counts READ/exploration tool calls cumulatively within one turn and advises at three levels, never blocking (browser debugging tools are excluded from counting): at 5 (plan_nudge_after) one PLANNING NUDGE names the planning tools that are actually registered — todowrite for simple tasks, taskflow_flow(action="plan") for multi-step ones — and fires only when the turn has neither called todowrite nor created a flow; at 7 it injects one <system-reminder source="delegation_pressure"> warning through its own mid-turn abefore_model path; at 12 the escalated system-reminder with stronger language. When the turn already dispatched TaskFlow steps, the 7/12 messages switch to the TaskFlow variant ("wait_all / dispatch, stop reading" instead of "call sessions_spawn"), because a dispatch IS delegation. A successful accepted/pending sessions_spawn or a successful TaskFlow dispatch wave (taskflow_step(action="dispatch"), or the plan's auto-dispatch) resets the counter so the main agent can inspect/verify and a later cycle re-arms; a failed spawn/dispatch does not reset. Writes alone do not reset it, and every graph invocation inside the turn accumulates until that hand-off or after_agent, which clears everything — including the plan-tracking flags — so a NEW turn is nudged to plan again. The env SHERRY_EVAL_DELEGATION_PRESSURE=1 remains the explicit eval-arm selector; the product main chain always includes the gate.
Active on the main agent and worker agents. When a model call returns truncated
(finish_reason == "length" / stop_reason == "max_tokens") with tool
calls, the tool-call JSON is garbage: executing it fails, the model re-issues
it, and each round burns IterationBudget — an unbounded retry spiral seeded
by nothing the turn guards watch. The middleware closes that spiral inside the
middleware layer:
- First call at the original
max_tokens; on truncation-with-tool-calls it re-calls the handler withmax_tokens = base × 2^attempt(baseMAIN_LLM_OUTPUT_MAX_TOKEN, default 8192; capped at 32768; max 3 retries). -
Bounded by construction: 4 handler calls total, the boost is capped, and
the re-calls happen inside
awrap_model_call, soIterationBudgetcharges +0 — no spiral into the budget. - The truncated intermediate result is discarded; the agent loop only sees the final (recovered) result, so nothing truncated reaches the checkpointer or a tool executor.
-
Streaming re-calls strip callbacks: the truncated first-call tokens are
already on the wire, so each re-call removes
request.config["callbacks"]to avoid duplicate output and restores the originals infinally(even on exception). The streaming/non-streaming decision reads theis_stream_turnflagStreamTurn.run()sets per session — children (ainvoke) never carry it and always take the non-streaming path. - Text-only truncation (no tool calls) is not a loop concern handled here; the service layer owns it via a bounded continuation re-stream (max 4).
Context overflow is a loop of its own: the provider rejects an oversized request, compression fires, the compacted context still overflows, and the provider errors again. Summarization bounds it in three stages — and the first one does not call an LLM at all:
| Stage | Mechanism | LLM cost | When it runs |
|---|---|---|---|
| 1. Overflow tail clip (P1-2) |
clip_overflow_tail (pub/func/message/overflow_clip.py) stubs the trailing contiguous ToolMessage batch |
none | before every non-fits route (T1/T2/T3) and before each T4/T5 recovery step |
| 2. Existing route |
truncate_tool_results_only / compact_only / compact_then_truncate
|
LLM call on compact routes (COMPRESSION_LLM_*, auxiliary fallback) |
only when the clip alone does not bring the estimate back under the line |
| 3. Forced recovery (T4/T5) | clip first, then compact + budget truncation, retried up to MAX_OVERFLOW_RETRIES (3) |
1 call per compact step | after a provider payload-too-large / context-overflow error |
The clip never removes, reorders, or injects a message: it replaces content through ToolMessage.model_copy, so id / tool_call_id / name / additional_kwargs survive and tool pairing plus the persistence watermark stay intact. An insufficient clip is discarded and the existing route runs on the exact original list.
Prevention at sampling time (models/LLMs/provider_repetition_penalty.py): every chat family sends frequency_penalty / presence_penalty (defaults 0.3 / 0.2) to OpenAI-compatible and Google providers, and Ollama's native repeat_penalty (1.1); Anthropic, Bedrock, an OpenAI reasoning model (o-series / gpt-5, whose API rejects the field) and an unknown gateway receive no field. The per-family .models keys (MAIN_LLM_FREQUENCY_PENALTY / _PRESENCE_PENALTY, likewise for auxiliary, TaskFlow and compression) override the global REPETITION_PENALTY one value at a time: empty means "use the default", and a set value must be a finite number in [-2, 2]. The model-configuration panel renders each pair as a number input that rejects non-numeric keystrokes and clamps out-of-range values. This lowers the probability of a repeated token before it is emitted; the guards below still react after the fact, so the two layers are complementary.
Cross-call detection (OutputRepetitionGuard, middleware in the worker pipeline):
- Content is normalized (NFKC → strip whitespace → strip punctuation) and hashed as a dual
head|tailMD5 over the first/last 500 chars, catching repetition at either end of long outputs. A rolling history of 30 hashes is kept per session. - WARN at 2 consecutive identical outputs (a nudge is appended); HALT at 3 (terminal message; the halt flag is sticky for the turn). Cross-call matching needs only 1 char of content, so even a single short sentence repeated across consecutive calls is a valid death-loop signal.
- Internal detection per output: duplicate-segment ratio > 0.6 (segments split on punctuation/newlines, minimum 6 segments), character runs ≥ 8, and short phrases (2-10 chars) repeated ≥ 5× consecutively. Content under 20 chars is skipped to avoid false positives. Internal warnings fire at most once per label per session.
-
Reasoning is tracked independently:
reasoning_content/reasoning/reasoning_textkwargs and inline<think>/<thinking>/<reasoning>wrappers feed separate history and warned flags. - The middleware owns exactly six session state keys (
SESSION_STATE_KEYS), which are released when a subagent-derived agent is torn down; no cross-middleware state leaks.
Stream layer (RepetitionGuardWrapper, wraps the main agent):
- Cuts internal repetition mid-stream, before chunks reach the client: one warning is injected, then the rest of that call's stream is suppressed.
- HALT short-circuit: once a halt is recorded for the turn, subsequent model calls return the halt message directly.
- Phantom-stream guard (opt-in, enabled in production): drops pre-update model text when a fresh dict-input invocation supersedes an in-flight run.
Registers a 1-minute timer per turn (timer_call_register) that compares heartbeat_iter / heartbeat_tool counters against the last observation. Any progress resets the stale counter; no progress for 7 cycles (~7 min) on an idle agent or 20 cycles (~20 min) while inside a tool sets a killed flag, and the next agent-loop entry raises HeartbeatTimeoutError, ending the turn gracefully. Registered on both main and worker agents; per-turn state resets in before_agent, the timer is unregistered in after_agent.
-
stopis session-scoped: it cancels that session's main turn and, on the USER stop path only, kills that session's killable subagent runs through the existing cascade kill (run_id-keyed task cancel + persisted KILLED/reconciliation). Other sessions' main agents and children are untouched; HITL resume / send-now keep their previous semantics. - Foreground
terminal,python_repland PTC now run in their own process group/session (POSIXstart_new_session; Windows a new process group). Cancellation/timeout sends SIGTERM to the GROUP, waits a bounded grace, then SIGKILLs it (Windowstaskkill /T /F).python_replno longer leaves its thread's child running. - Explicit
terminal(run_in_background=True)tasks are preserved on stop; session deletion kills their recorded process-group ID. Shell-internal&/nohupchildren are foreground and are killed with the group. bwrap/seatbelt are covered by the group plus the backend namespace; a deliberatesetsidescape is a documented P2 boundary. - A child killed by a user stop is reported as
[subagent:... interrupted](not failed) and queued for the next turn instead of starting an auto-turn. The main interrupted turn keeps the existing[interrupted]marker.
Injection drain (agent/middlewares/subagent_completion_drain/core.py): a before_model middleware that rehydrates and drains the session's SteeringQueue, injecting queued completion carriers right before the next model call. SQLite rows are marked CONSUMED on drain, so a checkpoint replay (HITL resume) can never re-inject the same completion. The middleware is fully fail-open: every failure is logged and swallowed, and the parent turn continues without injection. This closes the "parent waits forever for a child that already finished" loop.
Delivery retry + idempotency (agent/tools/subagent/announce/delivery.py, idempotency.py): busy-session completion announcements retry transient failures on a fixed ladder (5s / 10s / 20s, up to announce_retry_max=3; compaction errors use 1s / 2s / 4s / 8s). Permanent failures are never retried. Every delivery is keyed subagent_announce:{run_id}:gen:{generation} in a bounded in-memory idempotency set, so a retried announce cannot double-inject. Retries exhausted → run FAILED; soft retry cap → SUSPENDED; a run that hits max_announce_retry_count (10) retries, or a 24h age limit, is discarded. Together with the sweeper's orphan recovery, this bounds the delivery side of the subagent lifecycle.
runtime/process/periodic_backoff.py is a pure state machine (no threads, no I/O):
-
record_failure():consecutive_failures += 1;current_interval = min(base × factor^n, max_interval); exhausted whenconsecutive_failures >= max_consecutive_failures. -
record_success(): full reset. Defaults:factor=2.0,max_interval=7200s,max_consecutive_failures=5.
| Service | Base interval | Failure intervals | On exhaustion |
|---|---|---|---|
Heartbeat (skills/builtin/core/heartbeat/scripts/base.py) |
1800s (matches HeartbeatConfig.interval_s) |
3600s → 7200s → 7200s → 7200s | CRITICAL log ("paused ... manual recovery required"); the loop returns, so the service stops while the process lives on |
Subagent sweeper (agent/tools/subagent/registry/sweeper.py) |
60s (sweeper_interval_seconds) |
120s → 240s → 480s → 960s | CRITICAL log; _running=False ends the sweep task |
| Cron job breaker (below) | per-job, 5s base | degrade → disable | job auto-disabled |
Semantics worth knowing:
- The heartbeat records success inside its tick (which swallows its own errors), so only genuine tick failures count.
trigger_now()still works after a pause: a manual poke bypasses the sleeping loop. -
stop_sweeper()discards the backoff object (_backoff=None), so a manually restarted sweep begins fresh. The backoff object is created lazily (_get_backoff), never at import time. - In production the sweeper is started by
_schedule_sweeperinserver/trigger/channels/core.py, which hops the coroutine onto the main event loop (run_coroutine_threadsafe); the wiring is covered bytests/agent/tools/subagent/registry/test_sweeper_wiring.py. - Backoff state lives in Python objects: restarting the process resets heartbeat and sweeper breakers.
Per-job state machine in skills/builtin/core/cron/scripts/base.py (CronJobFailureState, memory-only; never written to cron_jobs.json except the enabled flag):
| Consecutive failures | Effect |
|---|---|
| 1-4 | Job fails normally: status marked error, WS bell notification |
| ≥ 5 (degraded) | Triggers are skipped while inside the backoff window: min(5000ms × 2^(n-5), 300000ms) since the last failure |
| ≥ 10 |
enabled=False is persisted; best-effort notification goes to the job's payload channel |
- Record-then-re-raise: the failure is recorded first, then the exception re-raised, so status/error reporting stays intact.
-
One-shot
atjobs are exempt (they can never fire twice, so a single failure is not a loop). - Success resets the state completely. A manual
enable_jobclears it; the RESTreset-failuresendpoint re-enables only when the breaker itself did the disabling, so operator disables are preserved.
runtime/process/crash_loop_breaker.py persists a boot journal to src/data/boot_lifecycle.json (keys: boots with {ts, clean, reason} entries, reason capped at 200 chars; last_exit_clean one-shot marker):
| Parameter | Value | Meaning |
|---|---|---|
TRIP_THRESHOLD |
3 | Unclean boots needed to trip |
WINDOW_S |
300 | within a 5-minute window |
RETENTION_S |
3600 | Boot records pruned after 1 hour |
Boot sequence (server/__main__.py), in order:
-
was_last_exit_clean()reads the one-shot marker beforerecord_boot(clean=..., reason="startup")consumes it. -
atexit.register(mark_clean_exit): a graceful shutdown marks the next boot clean. This is the self-heal; exit cleanly once, and old unclean records age out of the 5-minute window. - If tripped (3+ unclean boots within 5 min): set
SHERRY_HTTP_ONLY=1, log CRITICAL, and boot into HTTP-only mode:-
init_agent_core()still runs, so chat keeps working. - Curator and cron background init are skipped;
server/trigger/__init__skips channel-manager and subagent imports, so the heartbeat service and sweeper never start either. - HTTP/WS routes and the cron REST API stay up.
-
Manual reset: delete src/data/boot_lifecycle.json, or simply exit cleanly once and let the window decay.
| Layer | Mechanisms | What it catches |
|---|---|---|
| Middleware (in-graph, per turn) |
ToolGuardrails, IterationBudget, MaxTokensBoostMiddleware, OutputRepetitionGuard / RepetitionGuardWrapper, HeartbeatStaleness, SubagentCompletionDrain
|
tool pathologies, unbounded turns, truncated tool-call spirals, text death loops, stuck turns, missing completion injections |
| Process (background services) |
PeriodicBackoff (heartbeat, sweeper), cron failure breaker, announce retry ladder + idempotency |
service retry storms, failing scheduled jobs, duplicated completion delivery |
| Boot (process lifecycle) |
CrashLoopBreaker, server/__main__ gating, trigger.__init__ early exit |
crash-reboot loops |
| Infra / ops | cron REST hatches, HTTP-only env, state-file delete | stuck breaker state that needs an operator exit |
A loop can also come from finishing too early or from retrying without a bound. Four quality gates close that gap, mounted on the TaskFlow and subagent lifecycles; every one of them is fail-open, so a missing judge or an unreadable probe never blocks progress.
agent/tools/taskflow/step_judge.py is a TaskFlow-decision-LLM (TASKFLOW_LLM_*,
auxiliary fallback unless configured) discriminator at
temperature 0 that reviews a dispatched step's result against its
validation_criteria and returns pass / retry / block. It engages only
when the step carries criteria (set by taskflow_step(action="run_task") or
taskflow_step(action="resume")), so a plain step never pays for a judge call.
-
retryre-dispatches the step through the shared_retryseam, reusing the step's ownretry_countbudget (STEP_JUDGE["max_retries"], default 2) and injecting the judge's guidance into the replacement task viawith_judge_feedback(## Previous Attempt Feedback). An exhausted budget marks the stepblocked. -
blockmarks the stepblockedwith the judge's reason. - Fail-open: a model error or an unparseable response degrades to
pass.
STEP_JUDGE: max_retries=2, max_result_chars=8000,
evidence_aware=True.
agent/tools/subagent/spawn/completion_judge.py reviews a child run's latest
response before complete_subagent_run finalizes it and returns done /
continue. A continue verdict injects the judge's continuation_prompt as
the child's next human turn and the run continues on the same checkpoint
thread.
- The loop is bounded by
goal_max_turns(including the first turn), counted in_execute_subagent; when the budget is spent the run finalizes OK witherror="goal_loop_budget_exhausted". - It runs for every spawn: the completion judge is always engaged, and
sessions_spawnexposesgoal_max_turns(default 5) as the budget override. A single-turn budget (goal_max_turns=1) runs the child once. - Fail-open: a model error or an unparseable response degrades to
done, so a judge can never trap a subagent in the loop.
The ledger itself — the shared SQLite verification trail (src/data/registry.db (evidence_events table), WAL; immutable rows with lazy retention) whose staleness is derived on read — has its own
page: Evidence Ledger. What closes
the loop here is the gate that reads it:
taskflow_finish.py gates the DONE transition on three checks, in order:
| Gate | Checks | Reject reason |
|---|---|---|
| A — DAG completeness | every step is done or blocked
|
step(s) not done/blocked |
| B — no blocked steps | no step is blocked
|
step(s) are blocked |
| C — flow evidence | the flow's evidence has no FAIL and no [stale] row |
failing verification evidence / stale evidence
|
Every gate is fail-open: an unreadable ledger passes rather than blocking a
finish. An opt-in fourth check, Gate E, asks the TaskFlow decision model (TASKFLOW_LLM_*, auxiliary fallback) whether the
collected results satisfy the flow's description — it runs only for a flow of
GOAL_GATE["min_steps"] (3) steps or more, because a smaller flow's work is
already judged at the child level.
SubagentCompletionDrainMiddleware gates every drained completion batch against
the session's verification evidence: the carriers are injected verbatim, and
when the session has no passing evidence a mandatory-verification message is
appended after them. The gate is fail-open: an unavailable evidence lookup never
blocks the turn. Injected rows carry metadata.origin (quality_gate here,
subagent_completion / task_intent / todo_continuation elsewhere),
which is persisted and makes the chat render them as neutral cards rather than
as messages the user wrote.
Every non-empty plan ends with one SYSTEM [VERIFY] todo — there is NO
minimum work-item count, so a one-item plan is verified too
(metadata.kind="verify", last position, priority high). The todolist service
inserts it after every mutation (replace/add/patch/remove), keeps it
last, removes it (and kills its reviewer) only when the plan has no work item
left, and never inserts one for a :subagent:/:swarm: session. The model
cannot forge it — the tool schema has no metadata field, the store only writes
that column through a system-only argument, and a copied template line is
stripped from replace. Evidence travels in the model-writable notes field.
The main agent spawns a read-only reviewer, patches its child_session_key
into subagent_id, and waits. The transition barrier refuses completion until
that reviewer has finished and every work todo is terminal; a direct cancel is
refused unless the reviewer budget is exhausted or the whole plan was cancelled.
PlanContinuationEnforcer treats "verify pending + reviewer running" as a wait
(no directive; the completion notice resumes the session), drives the report
read when the reviewer is finished or its registry run is terminal, and after
TODOLIST_INFRA["max_verify_respawns"] (2) re-spawns injects
[SYSTEM DIRECTIVE: VERIFY BUDGET EXHAUSTED] with the degraded escape (run the
checks yourself, cancel verify, record NOT verified). A failed report re-opens
only the named todo_ids with their evidence; passed todos stay completed. A
cancelled verify blocks skill extraction (_detect_todo_all_complete).
| Guard | Altitude | State home | Reset when |
|---|---|---|---|
ToolGuardrails |
Turn (tool calls) |
state_register_mem (tool_guardrail_state) |
Every turn (before_agent) |
IterationBudget |
Turn (model-call count) | state_register_mem |
Every turn |
MaxTokensBoostMiddleware |
Model call (truncation) |
request.model_settings + is_stream_turn flag |
Per turn; flag cleared in _cleanup
|
OutputRepetitionGuard |
Turn + session (text) | 6 session keys | Halt flag per turn; hash history per session (released on subagent teardown) |
RepetitionGuardWrapper |
Stream call (text) | In-flight + halt key | Per model call |
HeartbeatStaleness |
Turn (wall clock) |
heartbeat_* keys + 1-min timer |
Every turn |
SubagentCompletionDrain |
Turn (injection) | SteeringQueue rows (SQLite) | Rows marked CONSUMED on drain |
| Announce retry + idempotency | Run (delivery) | In-memory idempotency set + run records | Success / retry cap / 24h expiry |
PeriodicBackoff (heartbeat / sweeper) |
Service (ticks) | Python object | Success / process restart / stop_sweeper
|
| Cron failure breaker | Job (triggers) | In-memory CronJobFailureState
|
Success / reset-failures / manual enable_job
|
CrashLoopBreaker |
Process (boots) | src/data/boot_lifecycle.json |
Clean-exit decay / file delete |
Within a turn, the turn guards are orthogonal and fire in parallel: OutputRepetitionGuard / RepetitionGuardWrapper guard the text, ToolGuardrails the tool calls, IterationBudget the count, and HeartbeatStaleness the wall clock. Whichever trips first ends the turn; none blocks the others. If all of them miss, the background breakers bound the next trigger, and the boot breaker bounds the next process.
-
All thresholds are code defaults (dataclass / constructor parameters); there are intentionally no env vars for them. Notably,
config/schema.py'smax_tool_iterations = 40is not consumed by the middleware (budgets are passed explicitly: 180 / 90 / 60), andHeartbeatConfig.interval_s = 1800matches the heartbeat service default but the service is constructed with defaults. -
TOOL_CALL_TIMEOUT_MINUTES(default 5 insherry.jsonc) is currently documentation-only: no code consumes it. The active per-tool bounds are constants (web search 15s, terminal 30s, python REPL 30s). Do not rely on it as a loop bound. - Workers get
OutputRepetitionGuardas middleware; the main agent is wrapped byRepetitionGuardWrapper(middleware hooks do not see raw stream chunks). -
MaxTokensBoostMiddlewareis the one guard with an env knob:MAIN_LLM_OUTPUT_MAX_TOKEN(default 8192) sets the boost base read at import time; the cap (32768) and retry count (3) are code constants. -
ToolGuardrailsknobs:warnings_enabled(default True),hard_stop_enabled(default False, BLOCK stays a block),recovery_mode_enabled(default True),recovery_max_violations(default 1),streak_warn_after(3),streak_max_warnings_per_turn(3),result_repetition_warn_after(3),result_repetition_block_after(6); a tool may override the signature threshold in its own metadata (terminal declares 5). Once the warning budget is spent, the exact repeated tool+args signature is BLOCKED for the rest of the turn; a different argument variant is still allowed. - Announce delivery knobs (subagent announce config):
announce_retry_max=3with 5s / 10s / 20s transient delays, plusmax_announce_retry_count=10and a 24h run expiry.
Manual recovery cheatsheet:
| Situation | Action |
|---|---|
| Cron job auto-disabled by the breaker |
POST /cron/reset-failures {"id": ...} (re-enables only breaker-disabled jobs) |
| Inspect a cron job's breaker state |
POST /cron/failure-state {"id": ...} (unknown job → 404, never-failed job → zeroed state) |
| Heartbeat paused (5 failed ticks) | Restart the process; trigger_now still fires one-shot ticks |
| Sweeper stopped (backoff exhausted) | Restart the process; a fresh sweep starts with fresh backoff |
| Boot gate tripped (HTTP-only) | Exit cleanly once, or delete src/data/boot_lifecycle.json
|
| Suite | Covers |
|---|---|
tests/agent/middlewares/test_tool_guardrails.py |
Pathology detection, escalation ladder, recovery mode |
tests/runtime/test_periodic_backoff.py |
Interval math, exhaustion, success reset |
tests/runtime/test_crash_loop_breaker.py |
Trip window / retention, clean marker, corrupt state |
tests/skills/builtin/core/cron/test_cron_failure_breaker.py |
Degrade → disable, reset semantics |
tests/skills/builtin/core/heartbeat/test_heartbeat_backoff.py |
Service backoff wiring, exhaustion pause |
tests/agent/tools/subagent/test_sweeper_backoff.py |
Sweeper backoff wiring, loop stop |
tests/agent/tools/subagent/registry/test_sweeper_wiring.py |
Sweeper startup wiring |
tests/server/test_crash_gating.py |
Boot gating, HTTP-only mode |
tests/server/test_cron_api.py |
Cron REST incl. failure-state / reset-failures |
tests/agent/middlewares/test_token_limit_continuation.py |
Truncation detection, text continuation loop, boost re-call incl. callback stripping |
tests/agent/tools/subagent/test_max_tokens_boost_wiring.py |
Child-agent middleware wiring, non-stream default |
-
Turn guards are turn-scoped by design: a fresh turn starts with fresh guard state. Cross-turn repetition is
OutputRepetitionGuard's domain (session-scoped history), not the tool guardrails'. -
In-memory breaker state does not survive restarts: guardrail/repetition/iteration state is turn- or session-scoped anyway; the cron failure counters are lost on process restart (though the persisted
enabledflag is not); heartbeat/sweeper backoff lives in Python objects. A restart is therefore always a reset, sometimes a too-generous one. - Exhaustion stops services until restart: a paused heartbeat or stopped sweeper has no runtime re-arm API ("manual recovery required" is literal). The process itself keeps serving.
- The crash gate is window-based: a crash loop spaced more than 5 minutes apart never trips it, and any supervisor that deletes the state file resets it. The file is both the breaker's memory and the manual escape hatch.
-
hard_stop_enableddefaults to False: in strict mode, only same-tool failures and hard-stop-converted BLOCKs reach HALT; other pathologies stop at BLOCK (subject to recovery mode). - Content normalization cuts both ways: stripping whitespace/punctuation makes hashing resilient to formatting noise, but a model that paraphrases its loop each time evades hash-based detection. Internal segment/run detectors partially cover this; fully paraphrased loops are out of scope.
-
Recovery mode gives the model room to fail: a stubborn pathology costs one managed retry before HALT. Operators who want the immediate wall should set
recovery_mode_enabled=False. -
TOOL_CALL_TIMEOUT_MINUTESis declared but unread: it exists insherry.jsonc(and is described in the root README), but no code consumes it today; the per-tool constants listed above are the real bounds. - HTTP-only mode is a reduced footprint, not a lock-down: chat, HTTP/WS routes, and cron REST stay up by design; the goal is breaking the crash loop, not air-gapping the process.
Generated from the repository's wiki/ tree. Source