NEW

SurrealDB 4 is here, introducing SurrealDB Earth and SurrealDS!

Learn more

How to build an agent loop with SurrealDB: a task graph for agents

AI
Tutorial

Nov 23, 20266 min read

Martin Schaer

Martin Schaer

Show all postsHow to build an agent loop with SurrealDB: a task graph for agents

An agent loop is a cycle where an AI agent picks up a task, does the work, records the result and asks for the next task, until nothing is left. To run one safely you need a shared task list that knows what depends on what. In SurrealDB that list is a graph, and the database itself enforces the rules.

Our newsletter

Get tutorials, AI agent recipes, webinars, and early product updates in your inbox every two weeks

A single prompt gets you a single answer. An agent loop gets you a finished piece of work: a feature specified, built, tested, documented and released, with agents doing the steps and people approving the ones that matter.

If you lead engineering, AI transformation or a product organisation, this is the difference between a demo and something you can put into a process. A loop is only as good as the thing that keeps it organised. Four questions decide whether you can trust it:

  • Who is working on what? Several agents can run in parallel without two of them doing the same job.

  • What can start now? Work only begins when everything it depends on is finished.

  • What happened? Every step leaves a record you can read later.

  • Who approved it? Agents stop at a review gate, and a person moves the work on.

You don't need to read the SQL to care about those four answers. If you're not hands-on, share the rest of this article with the team who would build it. It is written for them.

The loop itself is small: claim a task, work, report, repeat. Everything that makes it reliable lives in the task list. I keep that list in SurrealDB because the pieces fit in one place:

  • Tasks and their dependencies are a graph (a DAG, a directed acyclic graph), so "what is ready?" and "what slips if this slips?" are queries

  • Rules like "no cycles" and "no starting blocked work" are database events, so no prompt has to remember them

  • Claiming a task is a single write, so agents can't take the same one

  • The progress log lives on the task, so the audit trail and the work item are one record

Keeping it simple to get started, this post uses a single table. The same model grows into agents, runs and artefacts as you need them.

A task has a status, a priority, an optional assignee, a progress log, and a list of blockers: the tasks that must finish first. The edges point at prerequisites, so a task's blockers are its parents in the dependency graph.

Schema diagram of the task table, with blockers pointing back at task

The full definition is in the schema.surql gist. The part that does the work is one field:

DEFINE FIELD blockers ON task TYPE array<record<task>> DEFAULT []
    REFERENCE ON DELETE REJECT;

REFERENCE makes the link two-way. task:release.blockers lists what the release waits on, and task:api<~task lists what the API blocks, without defining a second field. ON DELETE REJECT stops anyone deleting a task that others still depend on.

The seed.surql gist loads a small project, shipping a "saved searches" feature. The API and the UI both wait for the data model, the tests wait for both, and the release waits for the tests and the docs.

spec → data_model → api ─┬→ tests ─┐
                   └→ ui ┘         ├→ release
                      api → docs ──┘

It asks for the ready queue: todo tasks whose blockers are all done or cancelled, most urgent first.

DEFINE FUNCTION fn::ready() {
    RETURN SELECT * FROM task
        WHERE status = 'todo'
        AND array::len(blockers[WHERE !(status INSIDE ['done', 'cancelled'])]) = 0
        ORDER BY priority ASC, created_at ASC;
};

On the seed data, only the spec is ready:

SELECT id, title, priority FROM fn::ready();
-- [{ id: task:spec, priority: 0, title: 'Write the spec for saved searches' }]

The queue is a query, not a table you keep in sync. When a blocker finishes, the next call to fn::ready() already includes whatever it unlocked.

They claim it. fn::claim picks the top ready task (or a specific one) and flips it to in_progress in a single statement, and only if it is still todo:

RETURN fn::claim('agent-1', NONE);        -- returns the spec, now in_progress
RETURN fn::claim('agent-2', task:spec);   -- returns NONE: it is already taken

I also tried it under load, on v4.0.1 with a single in-memory node, on 23 November 2026. Eight connections claimed the same task at once, three times over. Each time exactly one claim returned the task and the other seven returned NONE. A NONE on its own doesn't mean the work is done, so a loop should stop only when the ready queue is empty and no task is still open.

Two events on the table. The first keeps the graph acyclic: after a change to blockers, a task may not appear in its own chain of prerequisites. The second refuses to start or finish work that still has open blockers.

DEFINE EVENT task_unblocked ON task
    WHEN $event INSIDE ['CREATE', 'UPDATE'] AND $after.status INSIDE ['in_progress', 'review', 'done'] THEN {
        IF array::len($after.blockers[WHERE !(status INSIDE ['done', 'cancelled'])]) > 0 {
            THROW <string>$after.id + ' has open blockers';
        };
    };

An agent that tries to skip ahead gets an error instead of a half-built release:

UPDATE task:release SET status = 'in_progress';
-- Error while processing event task_unblocked: ... task:release has open blockers

UPDATE task:spec SET blockers = [task:release];
-- Error while processing event task_acyclic: ... blockers of task:spec form a cycle

This is the point I'd make to anyone building agents: put the rules in the database, not in the prompt. A prompt is a request. An event is a guarantee, for every agent, written in any framework.

Agents move a task to review and stop. A task in review still blocks its dependents, so nothing downstream starts until a person approves it:

UPDATE task:spec SET notes += { at: time::now(), by: 'agent-1', text: 'Spec drafted, 3 open questions listed' };
UPDATE task:spec SET status = 'review';
SELECT id FROM fn::ready();                 -- []  nothing new, the spec is waiting for a human

UPDATE task:spec SET status = 'done', notes += { at: time::now(), by: 'martin', text: 'Approved' };
SELECT id FROM fn::ready();                 -- [{ id: task:data_model }]

The notes field is the audit trail: who did what, and when. Approving the spec is what unblocked the data model. After that task is done, the API and the UI become ready together, so two agents can work in parallel.

Here is a sketch with the Python SDK. I ran it against the seed data, with a script approving each task in review, and it worked through all seven tasks to done. do_work is where your model and tools go.

import time
from surrealdb import Surreal

db = Surreal("ws://127.0.0.1:8000/rpc")
db.signin({"username": "root", "password": "root"})
db.use("agents", "loop")

def do_work(task):                      # call your LLM or tools here
    return f"finished: {task['title']}"

while True:
    claimed = db.query("RETURN fn::claim('agent-1', NONE)").execute()
    task = claimed[0] if claimed else None
    if task:
        db.query(
            "UPDATE $id SET notes += { at: time::now(), by: 'agent-1', text: $text }, status = 'review'",
            {"id": task["id"], "text": do_work(task)},
        ).execute()
    elif not db.query("SELECT id FROM task WHERE status IN ['todo', 'in_progress', 'review']").execute():
        break                           # nothing ready and nothing left
    else:
        time.sleep(1)                   # a human is reviewing, or other agents are working

That's it 🤯 The loop has no logic about dependencies, ordering or concurrency. All of that is in the schema. It also means you can swap the agent, the model or the language without touching the rules.

One thing I haven't covered: a task abandoned by a crashed agent stays in_progress until someone resets it. claimed_at is there so you can find those tasks and decide what the timeout should be.

Because the dependencies are a graph, the planning questions are one-liners:

RETURN task:data_model<~task;                      -- what it directly blocks
-- [task:api, task:ui]

RETURN task:data_model.{..+collect}<~task;         -- everything downstream, transitively
-- [task:api, task:ui, task:docs, task:tests, task:release]

RETURN task:release.{..+collect}.blockers;         -- everything it waits on, transitively
-- [task:tests, task:docs, task:api, task:ui, task:data_model, task:spec]

The second one answers "what slips if the data model slips?". The third answers "what has to happen before we can release?". Both are the questions a manager asks, and both come straight out of the same table the agents use.

All the queries above are in the queries.surql gist, in the order they ran, with the two expected errors marked. Load the schema, then the seed, then work through them one at a time. I ran everything on SurrealDB v4.0.1.

  • An agent loop is claim, work, report, repeat, and it is only as reliable as the task list behind it

  • Model tasks as a DAG: a blockers field, with REFERENCE to get the reverse direction

  • Make the ready queue a function, so it is always current

  • Claim with a single conditional update, so one agent gets each task

  • Put the rules in events, so no prompt has to remember them

  • Stop at review and let a person move the work on

Want to run this yourself? Load the three gists into a free instance and point your agent at fn::claim.

Our newsletter

Get tutorials, AI agent recipes, webinars, and early product updates in your inbox every two weeks