Repository navigation
feat(loops): run_agent_loop MCP tool + sequential loop service (#740 Phase 1) - #902
Merged
Merged
Conversation
11 tasks
dolho
force-pushed
the
feature/740-run-agent-loop
branch
from
May 25, 2026 07:15
0174ea4 to
d8016e1
Compare
dolho
added a commit
that referenced
this pull request
May 27, 2026
…e 1) Two CI gates were failing on PR #902: 1. `lint (sys.modules pollution check)` — test_loop_service.py used a bare `sys.modules.pop()` in its module-level src/backend bootstrap. The lint baseline rejects new bare sys.modules writes. Refactored to the sanctioned pattern (top-level `_STUBBED_MODULE_NAMES` list + autouse `_restore_sys_modules` fixture) so the swap can't leak into sibling test files. Precedent: test_telegram_webhook_backfill.py. Lint now reports `OK: 230 violation(s) in 65 file(s); baseline allows 237 — no new violations`. 2. `regression diff` — test_agent_cleanup_parity flagged the new `agent_loops.agent_name` column as unregistered with the #816 `cascade_delete` / `cascade_rename` registry. Without this, an agent's loop rows orphan on delete. Registered: AGENT_REFS: agent_loops.agent_name → Policy.CASCADE LINK_CHAINED_DELETES: agent_loop_runs.loop_id → agent_loops.agent_name `agent_loops.source_agent_name` is intentionally NOT registered (audit-trail / initiator only, like `chat_messages.user_id` — and the parity regex pin matches that semantic distinction). Local verification: 16/16 loop service tests pass; 4/4 parity tests pass; full lint output clean. Related to #740. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
dolho
marked this pull request as ready for review
May 27, 2026 11:34
dolho
added a commit
that referenced
this pull request
May 27, 2026
dolho
added a commit
that referenced
this pull request
May 27, 2026
…e 1) Two CI gates were failing on PR #902: 1. `lint (sys.modules pollution check)` — test_loop_service.py used a bare `sys.modules.pop()` in its module-level src/backend bootstrap. The lint baseline rejects new bare sys.modules writes. Refactored to the sanctioned pattern (top-level `_STUBBED_MODULE_NAMES` list + autouse `_restore_sys_modules` fixture) so the swap can't leak into sibling test files. Precedent: test_telegram_webhook_backfill.py. Lint now reports `OK: 230 violation(s) in 65 file(s); baseline allows 237 — no new violations`. 2. `regression diff` — test_agent_cleanup_parity flagged the new `agent_loops.agent_name` column as unregistered with the #816 `cascade_delete` / `cascade_rename` registry. Without this, an agent's loop rows orphan on delete. Registered: AGENT_REFS: agent_loops.agent_name → Policy.CASCADE LINK_CHAINED_DELETES: agent_loop_runs.loop_id → agent_loops.agent_name `agent_loops.source_agent_name` is intentionally NOT registered (audit-trail / initiator only, like `chat_messages.user_id` — and the parity regex pin matches that semantic distinction). Local verification: 16/16 loop service tests pass; 4/4 parity tests pass; full lint output clean. Related to #740. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
dolho
force-pushed
the
feature/740-run-agent-loop
branch
from
May 27, 2026 14:34
4b2b9ec to
579c8a1
Compare
…Phase 1)
Adds the third execution primitive alongside chat_with_agent (single
turn) and fan_out (parallel batch): sequential bounded repetition with
fire-and-disconnect semantics.
What ships
- POST /api/agents/{name}/loops — start a loop, 202 Accepted
- GET /api/agents/{name}/loops — list loops for an agent
- GET /api/loops/{loop_id} — status + per-run summaries
- POST /api/loops/{loop_id}/stop — graceful stop
- MCP tools: run_agent_loop, get_loop_status, stop_loop
(`src/mcp-server/src/tools/loops.ts`)
Modes
- Fixed: stop_signal unset → runs exactly max_runs (1–100).
- Until: stop_signal set → exits early when any iteration's response
contains the signal. Recommended sentinel: [[DONE]].
Execution model
- LoopService spawns an in-process asyncio.Task per loop.
- Each iteration dispatches through task_execution_service.execute_task()
with triggered_by='loop' and the parent loop_id, so iterations show up
on the timeline as normal schedule_executions rows tagged with their
parent loop. Iterations share the agent's max_parallel_tasks budget
via the standard capacity_manager admit/slot path.
- Template substitution before each iteration: {{run}} → 1-indexed,
{{previous_response}} → trailing 2000 chars of the previous response.
Cooperative stop
- POST /loops/{id}/stop flips an in-process should_stop flag; the
currently-executing iteration finishes (sequential — no mid-iteration
cancellation), the loop exits with stop_reason='user_stopped'.
Restart recovery
- cleanup_service _cleanup_loop() startup hook calls
db.mark_orphan_loops_interrupted() — any non-terminal agent_loops row
flips to status='interrupted' / stop_reason='interrupted'. Loops do
not auto-resume.
Schema
- New tables agent_loops + agent_loop_runs (db/schema.py +
_migrate_agent_loops_tables in db/migrations.py).
- schedule_executions gains a loop_id column + partial index
idx_executions_loop for the timeline join.
WebSocket events
- loop_run_completed per iteration (run_number, execution_id, cost,
duration_ms).
- loop_completed on terminal transition (status, stop_reason,
runs_completed). Routed through the existing manager.broadcast() →
Redis Streams bus.
Tests
- tests/unit/test_loop_service.py — 16 tests covering fixed/until modes,
template substitution, graceful stop, failure paths, restart recovery,
and get_status. All pass.
Docs
- requirements.md §33 (Sequential Agent Loops) with full Phase 1 scope.
- architecture.md: schema block + endpoints table + MCP tool row +
router/service module references + Cleanup Service row updated with
the orphan sweep.
- New feature flow docs/memory/feature-flows/run-agent-loop.md.
Out of scope for this PR
- Dedicated dashboard surface for loops (timeline tagging is the Phase 1
affordance).
- Auto-resume after restart.
- Cross-agent loops (agent target is implicitly 'self' via the
/api/agents/{name}/loops route).
Related to #740
Co-Authored-By: Claude Opus 4.7 <[email protected]>
…e 1) Two CI gates were failing on PR #902: 1. `lint (sys.modules pollution check)` — test_loop_service.py used a bare `sys.modules.pop()` in its module-level src/backend bootstrap. The lint baseline rejects new bare sys.modules writes. Refactored to the sanctioned pattern (top-level `_STUBBED_MODULE_NAMES` list + autouse `_restore_sys_modules` fixture) so the swap can't leak into sibling test files. Precedent: test_telegram_webhook_backfill.py. Lint now reports `OK: 230 violation(s) in 65 file(s); baseline allows 237 — no new violations`. 2. `regression diff` — test_agent_cleanup_parity flagged the new `agent_loops.agent_name` column as unregistered with the #816 `cascade_delete` / `cascade_rename` registry. Without this, an agent's loop rows orphan on delete. Registered: AGENT_REFS: agent_loops.agent_name → Policy.CASCADE LINK_CHAINED_DELETES: agent_loop_runs.loop_id → agent_loops.agent_name `agent_loops.source_agent_name` is intentionally NOT registered (audit-trail / initiator only, like `chat_messages.user_id` — and the parity regex pin matches that semantic distinction). Local verification: 16/16 loop service tests pass; 4/4 parity tests pass; full lint output clean. Related to #740. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The runner uses finalize_loop_run(..., execution_id=...) with COALESCE in the UPDATE SQL to bind execution_id late. The separate attach_execution_to_run() method on LoopOperations was never reached from production code — only the test stub referenced it. Removed: - src/backend/db/loops.py — attach_execution_to_run() method - src/backend/database.py — facade delegate - tests/unit/test_loop_service.py — _FakeDB mock override Net -16 lines. 20/20 tests + 4/4 cleanup-parity tests still pass. Live verification confirmed the COALESCE path works: execution_id was correctly bound on 3 separate loop iterations against the local stack (schedule_executions rows tagged with matching loop_id, triggered_by='loop'). Related to #740. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
dolho
force-pushed
the
feature/740-run-agent-loop
branch
from
May 28, 2026 07:10
579c8a1 to
5220951
Compare
|
Resolve by running |
Resolve MIGRATIONS conflict in src/backend/db/migrations.py: #902 (_migrate_agent_loops_tables) and #996 (_migrate_users_suspended_at) both appended near the list tail. Kept both functions and both name-keyed MIGRATIONS entries — they touch disjoint tables and the runner is order-independent. All other files auto-merged. Verified: 66 migrations (no dup names), 34 migration smoke tests (incl. concurrent race) + 16 loop + soft-delete tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
vybe
approved these changes
Jun 2, 2026
vybe
left a comment
Contributor
There was a problem hiding this comment.
Validated: follows 3-layer + MCP 3-surface invariants, additive schema, capacity path reused, full doc discipline (requirements §33 + architecture + feature-flow), 16 service tests. Merge conflict in migrations.py resolved keep-both (verified: 34 migration smoke tests incl. concurrent race + 28 loop/soft-delete tests pass, no dup migration names). APPROVE.
6 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds the third execution primitive alongside
chat_with_agent(single turn) andfan_out(parallel batch): sequential bounded repetition with fire-and-disconnect semantics. Implements #740 Phase 1.agent_loops+agent_loop_runsPOST → 202 + loop_id, then disconnectschedule_executionsrow tagged withloop_idSurface
POST /api/agents/{name}/loops— start a loop (202 +loop_id)GET /api/agents/{name}/loops— list loops for an agentGET /api/loops/{loop_id}— status + per-run summaries + last full responsePOST /api/loops/{loop_id}/stop— graceful stoprun_agent_loop,get_loop_status,stop_loopModes
stop_signalunset): runs exactlymax_runstimes (1–100).stop_signalset): exits early when any iteration's response contains the signal. Recommended sentinel[[DONE]].Template supports
{{run}}(1-indexed) and{{previous_response}}(trailing 2000 chars of the prior iteration's response).Execution model
LoopServicespawns an in-processasyncio.Taskper loop.task_execution_service.execute_task(triggered_by='loop', loop_id=...)→ goes throughcapacity_manageradmit/slot → standard execution.should_stopflag checked between iterations; current iteration finishes naturally.cleanup_servicestartup hook callsdb.mark_orphan_loops_interrupted()— any non-terminal row from a prior process flips tointerrupted. Loops do not auto-resume.Schema
agent_loops,agent_loop_runs.schedule_executions.loop_id TEXT+ partial indexidx_executions_loop._migrate_agent_loops_tables. Schema additions are additive — clean rollback.WebSocket events
loop_run_completedper iteration:{loop_id, agent_name, run_number, execution_id, cost, duration_ms, timestamp}.loop_completedon terminal:{loop_id, agent_name, status, stop_reason, runs_completed, timestamp}.manager.broadcast()→ Redis Streams bus (RELIABILITY-003).Tests
tests/unit/test_loop_service.py— 16 tests covering fixed/until modes, template substitution, graceful stop, failure paths (per-iteration failure + Python exception), restart recovery,get_status. All pass.Docs
requirements.md§33 (new section).architecture.md: schema block + endpoints table + MCP tools row + router/service module references + Cleanup Service row updated.docs/memory/feature-flows/run-agent-loop.md+ index entry + Recent Updates row.Out of scope (deferred)
loop_idon each iteration'sschedule_executionsrow); a follow-up PR can add a collapse-group affordance.interruptedis the Phase 1 semantics.agenttarget is implicitly'self'via the/api/agents/{name}/loopsroute shape, matchingfan_out's v1 stance.Test plan
schedule_executionsrows with matchingloop_id[[DONE]]→ loop exits withstop_signal_matchedPOST /api/loops/{id}/stopmid-loop → status flips tostoppedGETreturnsstatus=interruptedRelated to #740 — closes at the release that ships Phase 1.
🤖 Generated with Claude Code