Skip to content

feat: local agent ReAct loop with history management and context budgeting - #1030

Merged
malibio merged 2 commits into
mainfrom
feature/issue-1006-agent-react-loop
Apr 3, 2026
Merged

malibio merged 2 commits into
mainfrom
feature/issue-1006-agent-react-loop

Conversation

@malibio

@malibio malibio commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

Implements the core ReAct (Reason + Act) loop driving the local agent (#1006):

  • LocalAgentLoop (agent_loop.rs): Orchestrates inference + tool-call cycles (max 5 iterations). Parses streaming chunks into text and tool calls, executes tools via AgentToolExecutor, feeds results back for next inference round.
  • History management: 8k token budget (2k system + 6k history). Automatic summarization of older turns when budget exceeded, keeping recent 3 turns verbatim.
  • LocalAgentService: Session management facade with create_session, send_message, cancel, end_session, get_sessions. Per-session CancellationToken support.
  • Status transitions: Idle -> Thinking -> ToolExecution -> Streaming -> Idle, emitted via callback.
  • Prompt templates (prompt_templates.rs): System prompt, tool definition formatter, summarization prompt, tool result formatter.
  • 22 unit tests with mock ChatInferenceEngine and mock AgentToolExecutor covering single-turn, multi-step tool chains, max iteration limit, cancellation, history summarization trigger, and status transitions.

Also fixes pre-existing issues: Cargo.toml merge conflict, duplicate pub mod local_agent, missing PartialEq on LocalAgentStatus, Debug for StdioTransport, tempfile dev-dependency, temporary lifetime bug in context_assembly test, and cargo fmt across multiple files.

Test plan

  • cargo check -p nodespace-app -- clean, no warnings
  • cargo test -p nodespace-app -- local_agent::agent_loop local_agent::prompt_templates -- 22/22 pass
  • cargo test -p nodespace-app -- 155 passed, 3 failed (all pre-existing: context_assembly budget, transport buffering, tools direction)
  • cargo fmt -p nodespace-app -- --check -- clean

Closes #1006

@malibio

malibio commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1030 -- Local Agent ReAct Loop

Reviewer: Principal Engineer (Pragmatic Quality Framework)
Verdict: Approve with non-blocking suggestions


Overall Assessment

This is a well-structured, net-positive change. The ReAct loop implementation is sound, the trait-generic design is clean, and the 22-test suite covers the critical paths. The separation into LocalAgentLoop (stateless orchestrator) and LocalAgentService (session facade) is a good application of Single Responsibility Principle. The ancillary fixes (Cargo.toml merge conflict cleanup, cargo fmt, PartialEq derive, Debug for StdioTransport) are all sensible housekeeping.

Acceptance criteria coverage against issue #1006:

Criterion Status
Single-turn conversation (no tools) Covered: single_turn_no_tools test
Multi-step tool use with result feedback Covered: tool_call_then_final_response test
Chain of tool calls (search -> get -> respond) Covered: multi_step_tool_chain test
Max iteration limit (5 rounds) Covered: max_iteration_limit test
History summarization triggers at 6k tokens Covered: history_summarization_trigger test
Status transitions (Idle->Thinking->ToolExec->Streaming->Idle) Covered: two status transition tests
Streaming tokens forwarded correctly Covered: chunks forwarded via on_chunk callback
Session create/resume with persistent history Covered: service_send_message verifies session state persists
Cancellation via CancellationToken Covered: cancellation_stops_generation test
System prompt templates and tool definitions Covered: 7 prompt_templates tests

All acceptance criteria are met.


Findings

Suggested Improvements

1. [Improvement] try_lock can silently drop chunks (agent_loop.rs, lines 145, 385)

The chunk collection callback uses try_lock() on a tokio::sync::Mutex:

if let Ok(mut guard) = collected_for_cb.try_lock() {
    guard.push(chunk);
};

If the mutex is contended at the moment a chunk arrives, that chunk is silently discarded. While unlikely in practice (the callback runs sequentially within generate), this is a subtle correctness hazard. If the engine ever calls the callback from multiple threads, tool calls could be partially lost.

Suggestion: Since the generate trait contract calls on_chunk sequentially (it takes Box<dyn Fn(...) + Send>, not + Sync), the simpler fix is to use a std::sync::Mutex instead -- try_lock contention becomes impossible in a single-threaded callback. Alternatively, use .lock().await in a sync context via blocking_lock() (available on tokio::sync::Mutex).

2. [Improvement] Session removal in send_message is not panic-safe (agent_loop.rs, line 491-507)

The send_message method removes the session from the HashMap, runs run_turn, then reinserts it. If run_turn panics (rather than returning Err), the session is permanently lost from the map. This pattern is known as the "take-mutate-return" anti-pattern for concurrent containers.

Suggestion: Either use a scopeguard / drop guard to ensure the session is always reinserted:

let result = {
    let _guard = scopeguard::guard((), |_| {
        // Ensure session goes back even on panic
    });
    self.agent_loop.run_turn(...)
};

Or document this as a known limitation (acceptable for a pre-release codebase since panics in async code are typically caught by the Tokio runtime).

3. [Improvement] parse_chunks uses HashMap -- tool call ordering not guaranteed (agent_loop.rs, line 284-313)

Tool calls are accumulated in a HashMap<String, (String, String)> keyed by ID, then iterated. HashMap iteration order is non-deterministic, so if the model emits multiple tool calls in a single turn, they may be executed in a different order than the model intended.

Suggestion: Use IndexMap or a Vec<(String, String, String)> to preserve insertion order. This matters when tool calls have causal dependencies (e.g., create_node then update_node on the new ID).

4. [Improvement] System prompt is rebuilt every iteration (agent_loop.rs, lines 96-101, 120-128)

system_content is built once before the loop (good), but on each iteration messages is rebuilt by cloning the system message + the full session history. For large histories this creates significant allocation churn.

Suggestion: For now this is fine given the 8k token budget keeps things small. If performance becomes a concern, the system message could be prepended in-place rather than rebuilt each iteration.

5. [Improvement] Summarization always sends a Role::User message (agent_loop.rs, line 372-380)

The summarization prompt is sent as a Role::User message to the inference engine. Some models may respond differently to a Role::System summarization instruction. Consider using Role::System for the summarization request to signal this is infrastructure, not user input.

6. [Improvement] Missing test: session persistence after error (agent_loop.rs)

The send_message method correctly reinserts the session on both success and Err return. However, there is no test verifying that after an inference error, the session is still retrievable and can be used for subsequent messages. Adding a test for this would validate the "take-mutate-return" pattern works correctly in the error path.


Nitpicks

1. Nit: Unreachable code after the loop (agent_loop.rs, lines 268-277)

// Should not reach here, but just in case
on_status(LocalAgentStatus::Idle);

This code after the for loop is truly unreachable -- every iteration either returns early (no tool calls, max iteration reached) or continues. The for loop exhausts all MAX_TOOL_ITERATIONS iterations, and the last one always triggers the iteration == MAX_TOOL_ITERATIONS - 1 early return. Consider removing this dead code or converting the loop to a loop with an explicit counter so the compiler can verify exhaustiveness.

2. Nit: available_tools error silently swallowed (agent_loop.rs, line 93-95)

let tools = self.tool_executor.available_tools().await.unwrap_or_default();

If tool listing fails, the agent proceeds with no tools. This may be intentional (degrade gracefully) but should be documented with a comment or logged.

3. Nit: HISTORY_TOKEN_BUDGET vs TOTAL_TOKEN_BUDGET double-check in summarization (agent_loop.rs, lines 339-345)

The summarization function checks both history_tokens + system_tokens <= TOTAL_TOKEN_BUDGET and history_tokens <= HISTORY_TOKEN_BUDGET. The first check is redundant -- if history_tokens <= HISTORY_TOKEN_BUDGET (6k) and system tokens are within 2k, total is within 8k. Consider simplifying to just the HISTORY_TOKEN_BUDGET check for clarity.

4. Nit: tempfile added as dev-dependency (Cargo.toml)

tempfile is added to [dev-dependencies] but this PR does not add any tests that use tempfile. It was likely needed for pre-existing model_manager tests whose Cargo.toml reference was broken by the merge conflict fix. This is fine, just noting it for clarity.


Summary

This is solid work. The architecture is clean, the trait-generic design enables excellent testability, and the test coverage is comprehensive for the critical paths. The suggested improvements above are non-blocking -- the most impactful one is the HashMap ordering issue in parse_chunks (#3), which I would recommend addressing before merge since it could produce incorrect behavior with multi-tool turns. The rest can be addressed in follow-up work.

Status: Approve (non-blocking suggestions)


Reviewed with Pragmatic Quality Framework -- Principal Engineer Reviewer

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed: Approve with non-blocking suggestions. See detailed review comment above. The most impactful recommendation is switching parse_chunks from HashMap to an ordered collection to preserve tool call ordering in multi-tool turns.

malibio pushed a commit that referenced this pull request Apr 3, 2026
Switching from HashMap to Vec ensures tool calls with causal dependencies
execute in the order the model emitted them, not random HashMap iteration
order.

Addresses reviewer recommendation from PR #1030 review.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator Author

Review Feedback Addressed

✅ Fixed tool call ordering: replaced HashMap with Vec to preserve emission order (causal dependencies)
⏭️ Skipped try_lock() concern — sequential callback execution means no contention in practice
⏭️ Skipped session panic-safety — acceptable for pre-release, noted as future improvement
⏭️ Skipped summarization Role::User vs System — both work, minor semantic difference

Michael Libio and others added 2 commits April 4, 2026 01:51
…eting (closes #1006)

Implements the core ReAct (Reason + Act) loop driving the local agent:

- LocalAgentLoop: orchestrates inference + tool-call cycles (max 5 iterations),
  parses streaming chunks into text and tool calls, executes tools via
  AgentToolExecutor, and feeds results back for next inference round
- History management: 8k token budget (2k system + 6k history), automatic
  summarization of older turns when budget exceeded, keeping recent 3 turns
- LocalAgentService: session management facade with create/send/cancel/end/list,
  per-session CancellationToken support
- Status transitions: Idle -> Thinking -> ToolExecution -> Streaming -> Idle
- Prompt templates: system prompt, tool definition formatter, summarization prompt
- 22 unit tests with mock ChatInferenceEngine and mock AgentToolExecutor covering
  single-turn, multi-step tool chains, max iteration limit, cancellation,
  history summarization, and status transitions

Also fixes pre-existing issues:
- Resolve Cargo.toml merge conflict between #1001 and #1000
- Remove duplicate `pub mod local_agent` in lib.rs
- Add PartialEq derive on LocalAgentStatus for test assertions
- Add Debug impl for StdioTransport, tempfile dev-dependency
- Fix temporary lifetime in context_assembly test
- Apply cargo fmt to pre-existing formatting issues

Co-Authored-By: Claude <[email protected]>
Switching from HashMap to Vec ensures tool calls with causal dependencies
execute in the order the model emitted them, not random HashMap iteration
order.

Addresses reviewer recommendation from PR #1030 review.

Co-Authored-By: Claude <[email protected]>
@malibio
malibio force-pushed the feature/issue-1006-agent-react-loop branch from f0a2506 to 57662fe Compare April 3, 2026 23:51
@malibio
malibio merged commit a527bff into main Apr 3, 2026
@malibio
malibio deleted the feature/issue-1006-agent-react-loop branch April 3, 2026 23:51
malibio added a commit that referenced this pull request Jun 22, 2026
…eting (#1030)

* feat: local agent ReAct loop with history management and context budgeting (closes #1006)

Implements the core ReAct (Reason + Act) loop driving the local agent:

- LocalAgentLoop: orchestrates inference + tool-call cycles (max 5 iterations),
  parses streaming chunks into text and tool calls, executes tools via
  AgentToolExecutor, and feeds results back for next inference round
- History management: 8k token budget (2k system + 6k history), automatic
  summarization of older turns when budget exceeded, keeping recent 3 turns
- LocalAgentService: session management facade with create/send/cancel/end/list,
  per-session CancellationToken support
- Status transitions: Idle -> Thinking -> ToolExecution -> Streaming -> Idle
- Prompt templates: system prompt, tool definition formatter, summarization prompt
- 22 unit tests with mock ChatInferenceEngine and mock AgentToolExecutor covering
  single-turn, multi-step tool chains, max iteration limit, cancellation,
  history summarization, and status transitions

Also fixes pre-existing issues:
- Resolve Cargo.toml merge conflict between #1001 and #1000
- Remove duplicate `pub mod local_agent` in lib.rs
- Add PartialEq derive on LocalAgentStatus for test assertions
- Add Debug impl for StdioTransport, tempfile dev-dependency
- Fix temporary lifetime in context_assembly test
- Apply cargo fmt to pre-existing formatting issues

Co-Authored-By: Claude <[email protected]>

* address review: preserve tool call ordering with Vec instead of HashMap

Switching from HashMap to Vec ensures tool calls with causal dependencies
execute in the order the model emitted them, not random HashMap iteration
order.

Addresses reviewer recommendation from PR #1030 review.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Local agent ReAct loop with history management and context budgeting

1 participant