Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
# Cog-Loop Truncation Guard — Don't Ship Half-Sentences as Replies

**Status**: Planned
**Priority**: High — observed in production. The cog loop currently delivers truncated mid-sentence replies as if they were successful outcomes, leaving the operator with no signal that anything went wrong and no actionable recovery path.
**Effort**: Small (~80-120 LOC + tests)
**Status**: Implemented (2026-04-26)
**Priority**: High — observed in production.
**Effort**: ~140 LOC across `agent/cognitive.gleam`, `agent/cognitive/output.gleam`, `agent/types.gleam` + call-site updates and 9 tests.
**Source**: 2026-04-26 incident — operator asked for a comparative analysis of two long documents, the writer hit `max_tokens=4096` twice, the orchestrator decided to write directly and hit its own `max_tokens=2048` mid-sentence, and the cycle terminated cleanly with `## Springdrift × The Synthetic` as the visible reply.

## What Shipped

- `truncation_retried: Bool` on `PendingThink` mirrors the existing `empty_retried` flag.
- `handle_think_complete` detects `MaxTokens` with no tool calls. First hit triggers a retry with a scope-down nudge ("decompose into multiple turns OR tighten scope"). Second hit ships the deterministic admission instead of the truncated text.
- `output.build_truncation_admission` is the pure helper that builds the operator-facing reply. `[truncation_guard]` prefix lets operators recognise the failure mode.
- 5 pure tests for the admission text + 4 end-to-end tests driving the cog loop with mock providers that return `MaxTokens` on a controlled schedule. Proved retry-success, second-hit-admission, and the regression case (empty-response retry still works independently).
- Test discovery: `ensure_alternation` coalesces same-role messages, so the retry nudge ends up merged into the original user message. Test discriminator switched from message count to content match on the nudge sentinel string.

The original plan is preserved below for context.

## The Symptom

The operator uploaded `The_Synthetic_Mind.pdf` (≈9000 lines) and asked
Expand Down
370 changes: 225 additions & 145 deletions src/agent/cognitive.gleam

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions src/agent/cognitive/agents.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,7 @@ fn handle_memory_tools(
fallback_from: None,
output_gate_count: 0,
empty_retried: False,
truncation_retried: False,
node_type: pending_node_type(state, task_id),
),
),
Expand Down Expand Up @@ -551,6 +552,7 @@ fn handle_memory_tools(
fallback_from: None,
output_gate_count: 0,
empty_retried: False,
truncation_retried: False,
node_type: pending_node_type(state, task_id),
),
),
Expand Down Expand Up @@ -1429,6 +1431,7 @@ pub fn handle_agent_complete(
fallback_from: None,
output_gate_count: 0,
empty_retried: False,
truncation_retried: False,
node_type: state.cycle_node_type,
),
),
Expand Down Expand Up @@ -1692,6 +1695,7 @@ pub fn handle_user_answer(
fallback_from: None,
output_gate_count: 0,
empty_retried: False,
truncation_retried: False,
node_type: state.cycle_node_type,
),
),
Expand Down
2 changes: 2 additions & 0 deletions src/agent/cognitive/llm.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ pub fn proceed_with_model(
fallback_from: None,
output_gate_count: 0,
empty_retried: False,
truncation_retried: False,
node_type:,
),
),
Expand Down Expand Up @@ -213,6 +214,7 @@ pub fn handle_think_error(
fallback_from: Some(failed_model),
output_gate_count: 0,
empty_retried: False,
truncation_retried: False,
node_type:,
),
),
Expand Down
46 changes: 46 additions & 0 deletions src/agent/cognitive/output.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
import agent/cognitive_state.{type CognitiveState}
import frontdoor/types as frontdoor_types
import gleam/erlang/process
import gleam/int
import gleam/option.{type Option, Some}
import gleam/string
import llm/types as llm_types

/// Publish the cycle-terminal reply to Frontdoor. Inert when Frontdoor
Expand Down Expand Up @@ -72,3 +74,47 @@ pub fn publish_human_question(

@external(erlang, "springdrift_ffi", "generate_uuid")
fn generate_uuid() -> String

/// Build the deterministic admission text the cog loop sends when
/// the truncation guard fires twice in a single cycle. Pure function:
/// no LLM call, no I/O, so the admission itself cannot be truncated.
///
/// The `[truncation_guard]` prefix is operator-facing — it tells them
/// the reply was synthesised by the cog loop rather than written by
/// the model, so they can recognise the failure mode at a glance.
///
/// Inputs are everything the operator needs to act:
/// - `model`: the LLM that hit the cap (so they know which agent's
/// `max_tokens` to look at)
/// - `output_tokens`: the actual produced size (≈ the limit)
/// - `limit`: the configured cap, for direct comparison
/// - `tools_fired`: tool names dispatched in the cycle so far, so
/// the operator sees how much work was already done
pub fn build_truncation_admission(
model: String,
output_tokens: Int,
limit: Int,
tools_fired: List(String),
) -> String {
let tools_line = case tools_fired {
[] -> "(no tools dispatched)"
_ -> string.join(tools_fired, ", ")
}
"[truncation_guard] Your last request hit my output budget twice in"
<> " this cycle. I have research material in narrative memory but"
<> " couldn't fit the full synthesis into a reply.\n\n"
<> "Last attempt: "
<> model
<> " at output_tokens="
<> int.to_string(output_tokens)
<> ", limit="
<> int.to_string(limit)
<> ".\n"
<> "Tools used this cycle: "
<> tools_line
<> ".\n\n"
<> "Suggested next steps:\n"
<> " - Ask for a narrower scope (e.g. \"just <one subset>\")\n"
<> " - Raise max_tokens in .springdrift/config.toml ([agents.<name>])\n"
<> " - Ask me to break the work into multiple replies"
}
4 changes: 4 additions & 0 deletions src/agent/cognitive/safety.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,7 @@ pub fn handle_safety_gate_complete(
fallback_from: None,
output_gate_count: 0,
empty_retried: False,
truncation_retried: False,
node_type: pending_node_type,
),
),
Expand Down Expand Up @@ -506,6 +507,7 @@ pub fn handle_safety_gate_complete(
fallback_from: None,
output_gate_count: 0,
empty_retried: False,
truncation_retried: False,
node_type: pending_node_type,
),
),
Expand Down Expand Up @@ -561,6 +563,7 @@ pub fn handle_safety_gate_complete(
fallback_from: None,
output_gate_count: 0,
empty_retried: False,
truncation_retried: False,
node_type: pending_node_type,
),
),
Expand Down Expand Up @@ -1492,6 +1495,7 @@ pub fn handle_output_gate_complete(
fallback_from: None,
output_gate_count: modification_count + 1,
empty_retried: False,
truncation_retried: False,
node_type: state.cycle_node_type,
),
),
Expand Down
7 changes: 7 additions & 0 deletions src/agent/types.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,13 @@ pub type PendingTask {
fallback_from: Option(String),
output_gate_count: Int,
empty_retried: Bool,
/// True after the cog loop has retried once because the previous
/// LLM response was truncated by max_tokens with no tool calls.
/// On the second hit in the same cycle the truncation guard
/// stops retrying and ships a deterministic admission instead of
/// the truncated text. Mirrors `empty_retried` for the
/// max_tokens failure mode.
truncation_retried: Bool,
node_type: dag_types.CycleNodeType,
)
PendingAgent(task_id: String, tool_use_id: String, agent: String)
Expand Down
Loading
Loading