Skip to content

feat(loops): run_agent_loop MCP tool + sequential loop service (#740 Phase 1) - #902

Merged
vybe merged 4 commits into
devfrom
feature/740-run-agent-loop
Jun 2, 2026
Merged

vybe merged 4 commits into
devfrom
feature/740-run-agent-loop

Conversation

@dolho

@dolho dolho commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds the third execution primitive alongside chat_with_agent (single turn) and fan_out (parallel batch): sequential bounded repetition with fire-and-disconnect semantics. Implements #740 Phase 1.

Before After
Primitives single-turn, parallel batch + sequential bounded loop
Server-managed iteration state — agent_loops + agent_loop_runs
Caller blocking time per-call MCP timeout cap one POST → 202 + loop_id, then disconnect
Timeline visibility n/a each iteration is a normal schedule_executions row tagged with loop_id

Surface

  • POST /api/agents/{name}/loops — start a loop (202 + loop_id)
  • GET /api/agents/{name}/loops — list loops for an agent
  • GET /api/loops/{loop_id} — status + per-run summaries + last full response
  • POST /api/loops/{loop_id}/stop — graceful stop
  • MCP tools: run_agent_loop, get_loop_status, stop_loop

Modes

  • Fixed (stop_signal unset): runs exactly max_runs times (1–100).
  • Until (stop_signal set): 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

  • LoopService spawns an in-process asyncio.Task per loop.
  • Each iteration calls task_execution_service.execute_task(triggered_by='loop', loop_id=...) → goes through capacity_manager admit/slot → standard execution.
  • Cooperative stop: should_stop flag checked between iterations; current iteration finishes naturally.
  • Restart recovery: cleanup_service startup hook calls db.mark_orphan_loops_interrupted() — any non-terminal row from a prior process flips to interrupted. Loops do not auto-resume.

Schema

  • New tables: agent_loops, agent_loop_runs.
  • schedule_executions.loop_id TEXT + partial index idx_executions_loop.
  • Migration: _migrate_agent_loops_tables. Schema additions are additive — clean rollback.

WebSocket events

  • loop_run_completed per iteration: {loop_id, agent_name, run_number, execution_id, cost, duration_ms, timestamp}.
  • loop_completed on terminal: {loop_id, agent_name, status, stop_reason, runs_completed, timestamp}.
  • Routed through existing 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.
  • New flow docs/memory/feature-flows/run-agent-loop.md + index entry + Recent Updates row.

Out of scope (deferred)

  • Dedicated dashboard surface for loops — Phase 1 ships timeline tagging (loop_id on each iteration's schedule_executions row); a follow-up PR can add a collapse-group affordance.
  • Auto-resume after backend restart — explicit interrupted is the Phase 1 semantics.
  • Cross-agent loops — agent target is implicitly 'self' via the /api/agents/{name}/loops route shape, matching fan_out's v1 stance.

Test plan

  • Migration adds tables + loop_id column cleanly on backend reload
  • LoopService unit tests pass (16/16)
  • Live: start a 3-iteration fixed loop on a running stack → 3 schedule_executions rows with matching loop_id
  • Live: start an until-mode loop, agent responds with [[DONE]] → loop exits with stop_signal_matched
  • Live: POST /api/loops/{id}/stop mid-loop → status flips to stopped
  • Live: restart backend mid-loop → next GET returns status=interrupted
  • CI: lint + 6-seed pytest matrix + regression diff

Related to #740 — closes at the release that ships Phase 1.

🤖 Generated with Claude Code

@dolho
dolho force-pushed the feature/740-run-agent-loop branch from 0174ea4 to d8016e1 Compare May 25, 2026 07:15
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
dolho marked this pull request as ready for review May 27, 2026 11:34
@dolho dolho closed this May 27, 2026
@dolho dolho reopened this May 27, 2026
@dolho dolho closed this May 27, 2026
@dolho dolho reopened this May 27, 2026
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
dolho force-pushed the feature/740-run-agent-loop branch from 4b2b9ec to 579c8a1 Compare May 27, 2026 14:34
dolho and others added 3 commits May 28, 2026 10:10
…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
dolho force-pushed the feature/740-run-agent-loop branch from 579c8a1 to 5220951 Compare May 28, 2026 07:10
@dolho
dolho requested a review from vybe May 28, 2026 07:11
@github-actions

github-actions Bot commented Jun 2, 2026

Copy link
Copy Markdown

⚠️ Nightly unit-suite check skipped — merge conflict against dev.

Resolve by running git merge dev locally and pushing the result. The next nightly run will re-test once the conflict is gone.

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 vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@vybe
vybe merged commit 2aa0878 into dev Jun 2, 2026
14 checks passed
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.

2 participants