Agentic Architectures

Catalogue / Tools & Action

Session-Loop Harness

A fresh session each time; files on disk carry the work forward

Shape
loop
Model calls
1 setup session + 1 session per feature (max 30), each of tens of calls
Latency
high
Complexity
medium

Also known as Ralph loop, Initializer and coding agent

1

How can an agent keep building for days when its context lasts hours?

A project too large for one context is cut into sessions. A plain loop starts each session with an empty context. The session reads a feature list and progress notes from disk, completes one feature, tests it, and updates the files. The files are the only memory, and the list says when the project is done.

You may need it if

  • A long agent run slows down and forgets the goal as its context fills with old attempts.
  • The agent announces that the project is finished when a third of it is built.
  • A run stops halfway through a feature, and the next one cannot tell what was left broken.
2

When is a loop of fresh sessions the wrong tool?

Use it when

  • The work is a whole project that can be listed as many small features, each one testable on its own.
  • The agent can run the project and check a feature end to end, the way a user would.
  • The project starts from an empty repository, so the list and the notes describe everything that exists.

Avoid it when

  • The work is one issue on an existing repository and fits in one context. The files and the loop are then overhead.
    Use SWE Agent instead
  • The agent cannot run a check that can fail. Sessions then mark features as passing on their own word, and later sessions build on that.
  • The features are independent and several agents could build them at the same time. Here one session works at a time.
    Use Shared Task List instead
  • Nobody can yet say what the features are. The loop needs a list it can count down.
    Use Planning instead

What it costs

Model calls
1 setup session + 1 session per feature (max 30), each of tens of calls
Latency
high
Complexity
medium
3

How does work pass from one session to the next?

An initializer turns the request into a feature list, all marked failing, plus notes and a first commit. Then a plain loop starts session after session. Each one reads the files, builds and tests one feature, marks it and commits. Code reads the list: all passing ends the run, and so does the session cap.

tests thefeaturewhatworked andwhat brokesessionendsfeatures left:new emptysessionevery featurepassessession budgetused upRequest: The description of the project to build, or a plan that already lists what it must do.RequestInitializer: Runs once. Writes the feature list, the start script, the first progress note and the first commit.InitializerFeature list: One entry per feature, with the steps that test it and a pass mark. Every mark starts as failing.Feature listNotes and repository: The progress notes, the start script and the repository with its commit history.Notes andrepositorySession agent: Starts with an empty context. Reads the files, builds one failing feature, tests it and leaves the files up to date.Session agentEnd-to-end checks: Starts the project and carries out a feature's test steps as a user would.End-to-endchecksAll features pass?: Plain code. Reads the pass marks after each session and counts sessions.All featurespass?Finished project: The repository with every listed feature marked as passing, and the notes of each session.FinishedprojectUnfinished: The repository as it stands, the features still failing and the last notes, when the sessions run out.Unfinished
  1. Step 1 of 7

    The request becomes a list

    Asked for a room-booking web app, the initializer writes 24 features, such as "a user books a free room for one hour", each with its test steps. All are marked failing.

  2. Step 2 of 7

    The ground is prepared once

    The initializer also writes a script that starts the app, an empty progress note and a first commit. No later session has to work out how to run the project.

  3. Step 3 of 7

    A session starts from nothing

    Session 7 knows nothing of sessions 1 to 6. It reads the progress note, the last commits and the list, then starts the app to check that nothing was left broken.

  4. Step 4 of 7

    One feature, tested as a user would

    It picks one failing feature, "cancel a booking", builds it, then opens the app and cancels a booking for real. The check fails once on a stale page, and it fixes that.

  5. Step 5 of 7

    The files are left in order

    The session changes one pass mark, commits, and writes in the note what it did and what it saw. It changes nothing else in the list. Then it ends.

  6. Step 6 of 7

    Plain code decides what comes next

    The loop reads the list. Seventeen features still fail, so it starts session 8 with an empty context and the same instructions.

  7. Step 7 of 7

    Two exits

    When all 24 marks say passing, the project leaves as finished. After 30 sessions, or 3 in a row with no new mark, it leaves as unfinished with the list of what still fails.

What each part does
Request
The description of the project to build, or a plan that already lists what it must do.
Initializer
Runs once. Writes the feature list, the start script, the first progress note and the first commit.
Feature list
One entry per feature, with the steps that test it and a pass mark. Every mark starts as failing.
Notes and repository
The progress notes, the start script and the repository with its commit history.
Session agent
Starts with an empty context. Reads the files, builds one failing feature, tests it and leaves the files up to date.
End-to-end checks
Starts the project and carries out a feature's test steps as a user would.
All features pass?
Plain code. Reads the pass marks after each session and counts sessions.
Finished project
The repository with every listed feature marked as passing, and the notes of each session.
Unfinished
The repository as it stands, the features still failing and the last notes, when the sessions run out.
  • Initializer → Feature list: every feature, marked failing
  • Initializer → Notes and repository: start script, notes, first commit
  • Initializer → Session agent: first session
  • Feature list → Session agent: what still fails
  • Notes and repository → Session agent: notes and recent commits
  • Session agent → End-to-end checks: tests the feature
  • End-to-end checks → Session agent: what worked and what broke
  • Session agent → Feature list: one pass mark
  • Session agent → Notes and repository: commit and progress note
  • Session agent → All features pass?: session ends
  • Feature list → All features pass?: pass marks
  • All features pass? → Session agent: features left: new empty session
  • All features pass? → Finished project: every feature passes
  • All features pass? → Unfinished: session budget used up

Where it connects

Entry
request
TaskPlan

A project to build from an empty repository, described well enough to list its features. A plan, if given, is used as the basis of the feature list.

Exit
done
DocumentOutcome

When: Every feature in the list is marked as passing.

The repository with its commit history, the feature list with all marks passing, and the progress notes of every session.

Exit
unfinished
Verdict

When: The session budget is used up, or several sessions in a row added no passing feature, with features still failing.

A report that the project is not complete, with the features still failing, the last progress note and the state of the repository.

Memory kept between runs
features
Plan

The full list of features with test steps and one pass mark each. Sessions may change a mark and nothing else. Kept on disk between sessions and after the run.

Memory kept between runs
progress
Document

The repository with one commit per session, the start script and the dated progress notes. Kept on disk between sessions and after the run.

4

What do I ask my assistant to set up?

The agents to launch

Initializer

Do not build the project. Write a feature list that covers the whole request: one entry per feature with a description, the steps a user follows to test it, and a pass mark set to false. Write a script that starts the project and an empty progress note. Commit these files.

Sees: The request and an empty repository. Nothing else.

Session agent, one new instance per session, up to 30, never two at once

You have no memory of earlier sessions. Read the progress note, the recent commits and the feature list. Start the project and check that it still works. Build one failing feature. Test it as a user would. Only then set its mark to passing. Never edit or delete a feature. Commit, and write what you did in the progress note.

Sees: The repository, the feature list and the progress note as they are on disk. No earlier conversation.

A prompt you can paste

Works with any assistant that can launch sub-agents. It contains the agents, the procedure and the stop rule above.

Framework-agnostic prompt
You are the orchestrator of a multi-agent workflow that follows the "Session-Loop Harness" architecture.
Launch every agent listed below as a separate sub-agent with its own context. Give each agent only the context stated for it. Do not do an agent's work yourself. If you cannot launch sub-agents, play each agent in a clearly separated turn and never let it use what is withheld from it.

# Task
[Describe your task here]

# Session-Loop Harness
A fresh session each time; files on disk carry the work forward.
Input: the task above. It must provide: A project to build from an empty repository, described well enough to list its features. A plan, if given, is used as the basis of the feature list. If something essential is missing, ask for it before starting.

Agents to launch:
- Initializer: Do not build the project. Write a feature list that covers the whole request: one entry per feature with a description, the steps a user follows to test it, and a pass mark set to false. Write a script that starts the project and an empty progress note. Commit these files.
  Context for this agent: The request and an empty repository. Nothing else.
- Session agent (one new instance per session, up to 30, never two at once): You have no memory of earlier sessions. Read the progress note, the recent commits and the feature list. Start the project and check that it still works. Build one failing feature. Test it as a user would. Only then set its mark to passing. Never edit or delete a feature. Commit, and write what you did in the progress note.
  Context for this agent: The repository, the feature list and the progress note as they are on disk. No earlier conversation.

Procedure:
1. Create an empty repository. Launch the initializer on the request. Check that the feature list exists and that every mark is failing.
2. Keep a copy of the feature descriptions and test steps, so that later changes to them can be detected and undone.
3. Launch a session agent in a new context with the same fixed instructions. Give it no summary of earlier sessions.
4. When the session ends, read the feature list. If the descriptions or steps changed, restore them. Count the passing marks.
5. If features still fail, start the next session. Count the sessions, and the sessions in a row that added no passing mark.
6. When every mark is passing, release the repository as finished. Otherwise, at the limit, release it as unfinished with the list of failing features.

Stop rule: Stop when every feature is marked as passing. Stop also after 30 sessions, or after 3 sessions in a row that add no passing feature, and report the project as unfinished.

Exits:
- `done`, when: Every feature in the list is marked as passing. Deliver: The repository with its commit history, the feature list with all marks passing, and the progress notes of every session.
- `unfinished`, when: The session budget is used up, or several sessions in a row added no passing feature, with features still failing. Deliver: A report that the project is not complete, with the features still failing, the last progress note and the state of the repository.

# Final deliverable
The repository, the feature list with its marks and the progress notes. If unfinished, the list of features still failing and the last note, stated first.

The same thing in code

LangGraph, python, package langgraph
import json
from typing import TypedDict

from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage
from langchain_core.tools import tool
from langgraph.graph import END, START, StateGraph

model = init_chat_model("anthropic:claude-sonnet-5-5")
FILES: dict[str, str] = {}  # the project folder, path -> contents: plug in a real directory under git
MAX_SESSIONS, MAX_IDLE = 30, 3

INIT = ("Do not build the project. Write features.json: a list that covers the whole request, one entry per "
        "feature with 'description', 'steps' (what a user does to test it) and 'passes' set to false. "
        "Write start.sh, which starts the project, and an empty progress.md.")
SESSION = ("You have no memory of earlier sessions. Read progress.md and features.json. Check that the project "
           "still works. Build ONE failing feature. Test it as a user would with run_check. Only then set its "
           "'passes' to true. Never edit or delete a feature. Append what you did to progress.md.")


@tool
def read_file(path: str) -> str:
    """Read one file of the project."""
    return FILES.get(path, "no such file")


@tool
def write_file(path: str, content: str) -> str:
    """Create or overwrite one file of the project."""
    FILES[path] = content
    return "written"


@tool
def run_check(steps: str) -> str:
    """Start the project and carry out these steps as a user would. Returns what happened."""
    return "stub: no end-to-end check wired"


initializer = create_agent(model, [read_file, write_file], system_prompt=INIT)
session_agent = create_agent(model, [read_file, write_file, run_check], system_prompt=SESSION)


def marks() -> tuple[int, int]:
    features = json.loads(FILES.get("features.json", "[]"))
    return sum(1 for f in features if f["passes"]), len(features)


class State(TypedDict):
    request: str
    sessions: int
    idle: int  # sessions in a row that added no passing feature
    status: str


async def initialize(state: State) -> dict:
    await initializer.ainvoke({"messages": [HumanMessage(state["request"])]})
    return {"sessions": 0}


async def session(state: State) -> dict:
    before, _ = marks()
    # a new message list each time: the session starts empty, and only FILES carries over
    await session_agent.ainvoke({"messages": [HumanMessage("Start your session.")]}, {"recursion_limit": 120})
    after, _ = marks()
    return {"sessions": state["sessions"] + 1, "idle": 0 if after > before else state["idle"] + 1}


def gate(state: State) -> str:  # plain code reads the list; no model decides that the project is done
    passing, total = marks()
    if total and passing == total:
        return "done"
    if state["sessions"] >= MAX_SESSIONS or state["idle"] >= MAX_IDLE:
        return "unfinished"
    return "session"


async def done(state: State) -> dict:
    return {"status": "done"}


async def unfinished(state: State) -> dict:
    return {"status": "unfinished"}


builder = StateGraph(State)
builder.add_node("initialize", initialize)
builder.add_node("session", session)
builder.add_node("done", done)
builder.add_node("unfinished", unfinished)
builder.add_edge(START, "initialize")
builder.add_edge("initialize", "session")
builder.add_conditional_edges("session", gate, ["session", "done", "unfinished"])
builder.add_edge("done", END)
builder.add_edge("unfinished", END)
graph = builder.compile()


async def run(request: str) -> dict:
    s = await graph.ainvoke({"request": request, "sessions": 0, "idle": 0, "status": ""}, {"recursion_limit": 100})
    features = json.loads(FILES.get("features.json", "[]"))
    failing = [f["description"] for f in features if not f["passes"]]
    return {"status": s["status"], "sessions": s["sessions"], "failing": failing, "notes": FILES.get("progress.md", "")}

Replace FILES with a real folder under git and wire run_check to the running project. Keep a copy of the feature descriptions and restore them if a session edits them.

Claude Agent SDK, python, package claude-agent-sdk
import json
from pathlib import Path

from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query

PROJECT = Path("project")  # an empty git repository; everything the sessions share lives here
MAX_SESSIONS, MAX_IDLE = 30, 3

INIT = ("Do not build the project. Write features.json: a list that covers the whole request, one entry per "
        "feature with 'description', 'steps' (what a user does to test it) and 'passes' set to false. "
        "Write start.sh, which starts the project, and an empty progress.md. Commit these files.")
SESSION = ("You have no memory of earlier sessions. Read progress.md, the recent git log and features.json. "
           "Run start.sh and check that the project still works. Build ONE failing feature. Test it as a user "
           "would. Only then set its 'passes' to true. Never edit or delete a feature. Commit, and append what "
           "you did to progress.md.")


async def session(system: str, prompt: str) -> str:
    # every call is a new session with an empty context; only the files in PROJECT carry over
    options = ClaudeAgentOptions(
        system_prompt=system, cwd=PROJECT, permission_mode="acceptEdits",
        allowed_tools=["Read", "Write", "Edit", "Glob", "Grep", "Bash"], max_turns=200,
    )
    async for msg in query(prompt=prompt, options=options):
        if isinstance(msg, ResultMessage):
            return msg.result or ""
    raise RuntimeError("no result")


def read_features() -> list[dict]:
    path = PROJECT / "features.json"
    return json.loads(path.read_text()) if path.exists() else []


def locked(features: list[dict]) -> list[tuple[str, str]]:
    return [(f["description"], json.dumps(f["steps"])) for f in features]


async def run(request: str) -> dict:
    await session(INIT, request)
    reference = locked(read_features())  # sessions may change the pass marks and nothing else
    idle, used = 0, 0
    while used < MAX_SESSIONS and idle < MAX_IDLE:
        features = read_features()
        if features and all(f["passes"] for f in features):  # the gate: plain code reads the list
            return {"status": "done", "sessions": used, "failing": []}
        before = sum(1 for f in features if f["passes"])
        await session(SESSION, "Start your session.")
        used += 1
        after = read_features()
        if locked(after) != reference:
            raise RuntimeError("a session edited the feature list: restore it from the last good commit")
        idle = 0 if sum(1 for f in after if f["passes"]) > before else idle + 1
    features = read_features()
    failing = [f["description"] for f in features if not f["passes"]]
    status = "done" if features and not failing else "unfinished"
    return {"status": status, "sessions": used, "failing": failing}

Run it in a sandbox: the sessions use Bash inside PROJECT. Give them a browser tool if features can only be checked through the user interface.

OpenAI Agents SDK, python, package openai-agents
import json

from agents import Agent, Runner, function_tool

FILES: dict[str, str] = {}  # the project folder, path -> contents: plug in a real directory under git
MAX_SESSIONS, MAX_IDLE = 30, 3


@function_tool
def read_file(path: str) -> str:
    """Read one file of the project."""
    return FILES.get(path, "no such file")


@function_tool
def write_file(path: str, content: str) -> str:
    """Create or overwrite one file of the project."""
    FILES[path] = content
    return "written"


@function_tool
def run_check(steps: str) -> str:
    """Start the project and carry out these steps as a user would. Returns what happened."""
    return "stub: no end-to-end check wired"


initializer = Agent(
    name="Initializer",
    instructions="Do not build the project. Write features.json: a list that covers the whole request, one entry "
                 "per feature with 'description', 'steps' (what a user does to test it) and 'passes' set to "
                 "false. Write start.sh, which starts the project, and an empty progress.md.",
    tools=[read_file, write_file])
session_agent = Agent(
    name="Session agent",
    instructions="You have no memory of earlier sessions. Read progress.md and features.json. Check that the "
                 "project still works. Build ONE failing feature. Test it as a user would with run_check. Only "
                 "then set its 'passes' to true. Never edit or delete a feature. Append what you did to "
                 "progress.md.",
    tools=[read_file, write_file, run_check])


def read_features() -> list[dict]:
    return json.loads(FILES.get("features.json", "[]"))


async def run(request: str) -> dict:
    await Runner.run(initializer, request, max_turns=30)
    idle, used = 0, 0
    while used < MAX_SESSIONS and idle < MAX_IDLE:
        features = read_features()
        if features and all(f["passes"] for f in features):  # the gate: plain code reads the list
            break
        before = sum(1 for f in features if f["passes"])
        # a new run with no earlier messages: the session starts empty, and only FILES carries over
        await Runner.run(session_agent, "Start your session.", max_turns=60)
        used += 1
        idle = 0 if sum(1 for f in read_features() if f["passes"]) > before else idle + 1
    features = read_features()
    failing = [f["description"] for f in features if not f["passes"]]
    status = "done" if features and not failing else "unfinished"
    return {"status": status, "sessions": used, "failing": failing, "notes": FILES.get("progress.md", "")}

Replace FILES with a real folder under git and wire run_check to the running project. Do not pass a session object to Runner.run: each session must start empty.

Vercel AI SDK, typescript, package ai
import { anthropic } from '@ai-sdk/anthropic';
import { generateText, isStepCount, tool } from 'ai';
import { z } from 'zod';

const model = anthropic('claude-sonnet-5-5');
const FILES = new Map<string, string>(); // the project folder, path -> contents: plug in a real directory under git
const MAX_SESSIONS = 30;
const MAX_IDLE = 3;

const INIT =
  'Do not build the project. Write features.json: a list that covers the whole request, one entry per ' +
  "feature with 'description', 'steps' (what a user does to test it) and 'passes' set to false. " +
  'Write start.sh, which starts the project, and an empty progress.md.';
const SESSION =
  'You have no memory of earlier sessions. Read progress.md and features.json. Check that the project ' +
  'still works. Build ONE failing feature. Test it as a user would with runCheck. Only then set its ' +
  "'passes' to true. Never edit or delete a feature. Append what you did to progress.md.";

const projectTools = {
  readFile: tool({
    description: 'Read one file of the project.',
    inputSchema: z.object({ path: z.string() }),
    execute: async ({ path }) => FILES.get(path) ?? 'no such file',
  }),
  writeFile: tool({
    description: 'Create or overwrite one file of the project.',
    inputSchema: z.object({ path: z.string(), content: z.string() }),
    execute: async ({ path, content }) => { FILES.set(path, content); return 'written'; },
  }),
  runCheck: tool({
    description: 'Start the project and carry out these steps as a user would. Returns what happened.',
    inputSchema: z.object({ steps: z.string() }),
    execute: async () => 'stub: no end-to-end check wired',
  }),
};

type Feature = { description: string; steps: string[]; passes: boolean };
const readFeatures = (): Feature[] => JSON.parse(FILES.get('features.json') ?? '[]');
const passing = () => readFeatures().filter((f) => f.passes).length;

export async function run(request: string) {
  await generateText({ model, instructions: INIT, prompt: request, tools: projectTools, stopWhen: isStepCount(30) });
  let used = 0;
  let idle = 0;
  while (used < MAX_SESSIONS && idle < MAX_IDLE) {
    const features = readFeatures();
    if (features.length > 0 && features.every((f) => f.passes)) break; // the gate: plain code reads the list
    const before = passing();
    // a new call with no earlier messages: the session starts empty, and only FILES carries over
    await generateText({
      model,
      instructions: SESSION,
      prompt: 'Start your session.',
      tools: projectTools,
      stopWhen: isStepCount(60),
    });
    used++;
    idle = passing() > before ? 0 : idle + 1;
  }
  const features = readFeatures();
  const failing = features.filter((f) => !f.passes).map((f) => f.description);
  const status = features.length > 0 && failing.length === 0 ? 'done' : 'unfinished';
  return { status, sessions: used, failing, notes: FILES.get('progress.md') ?? '' };
}

Replace FILES with a real folder under git and wire runCheck to the running project. Keep a copy of the feature descriptions and restore them if a session edits them.

Snippets are generated when the site is built and type-checked against the SDK versions listed in the repository. Treat them as a starting skeleton.

What goes wrong

  • A session that tries to build everything at once runs out of context in the middle of a feature. Ask for one feature per session.
  • A session can make a feature pass by rewriting its entry. Let sessions change the pass mark only, and compare the rest with your copy.
  • A mark set after a unit test alone hides features that fail in real use. Require a test through the running project.
  • A session that ends without a commit and a note leaves the next one to guess. Make both the last steps of the instructions.
  • Without a session cap, a loop that has stopped making progress runs until someone notices. Count the sessions that add nothing.

Chain it

It can take the result of

On a condition

Source