Agentic Architectures

Catalogue / Tools & Action

Recoverable Execution

Go back to a saved point, restore the world, keep the lesson

Shape
loop
Model calls
1 per step (capped at 40) + 1 per review (every 6 steps, or when the actor asks)
Latency
high
Complexity
high

Also known as AgentRewind, Rollback-induced reflection

1

What if one bad step, found late, has already damaged the workspace?

On a long task, a wrong step leaves its mark on the files and on the agent's context. The harness saves both together before every action. When the path is judged lost, it restores both to a chosen earlier point and writes what the abandoned stretch taught into a memory that the restore does not erase.

You may need it if

  • An agent notices at step 30 that step 22 broke something, and every step in between built on it.
  • Restarting the whole task repeats twenty steps of sound work to undo one mistake.
  • After a failure the agent explains what went wrong, but the files it damaged stay damaged.
2

When is rolling back the wrong answer to a mistake?

Use it when

  • The task runs for dozens of steps, and a late discovery can make many earlier steps worthless.
  • The agent works in a place the harness controls and can snapshot, such as a folder, a container or a test database.
  • Something shows that a path is failing, such as a validator, repeated errors or actions that change nothing.

Avoid it when

What it costs

Model calls
1 per step (capped at 40) + 1 per review (every 6 steps, or when the actor asks)
Latency
high
Complexity
high
3

How does a run go back without forgetting why?

The actor works step by step. Before each action the harness saves the workspace and the context as one checkpoint. When a review is due, a reviewer decides to continue or to roll back, and to which point. Files and context return to it. The lesson goes to a memory kept outside the checkpoints.

next actionasks for areviewtask completeno review duereview due,rollbacks leftstep budgetused upcontinue,or resumefrom thepointTask: A long task to carry out in a workspace that the harness can save and restore, with a plan if there is one.TaskActor: Chooses one action at a time, asks for a review when its path looks lost, or declares the task complete.ActorReflection memory: What abandoned paths taught: facts about the environment, routes already tried and why the last one failed.ReflectionmemoryWorkspace: The controlled environment in which actions run: files, a container or a test database.WorkspaceCheckpoint store: One entry per step, saved before the action runs: the workspace and the actor's context, kept as a pair.CheckpointstoreReview due?: Plain code. Counts steps and rollbacks, and sends the run to a review at fixed intervals or on request.Review due?Reviewer: Judges whether the path can still succeed. If not, names the cause, picks the restore point and writes the lesson.ReviewerResult: The actor's final answer with the log of the steps on the path that was kept, and the rollbacks made.ResultNot completed: The report of a run that used all its steps, with the reflection memory and the state of the workspace.Not completed
  1. Step 1 of 6

    The actor starts working

    The task is to load 40 CSV exports into a new SQLite file inside a project folder. The actor reads the task and the reflection memory, which is empty, and picks a first action.

  2. Step 2 of 6

    Every action leaves a restore point

    Before each action runs, the harness saves the folder and the actor's context under the same step number. The actor does nothing for this and does not see it happen.

  3. Step 3 of 6

    A review comes due

    Plain code counts the steps. Six steps after the last review, a review is due. At step 30 the import check shows swapped days and months, and the actor asks for one itself.

  4. Step 4 of 6

    The reviewer picks the point

    The reviewer reads the log and the restore points. The cause is step 22, a script that rewrote every date column. It picks point 22, saved just before that script ran.

  5. Step 5 of 6

    The world goes back, the lesson stays

    The folder and the context return to point 22. Steps 22 to 30 are gone. The memory, kept outside, now says that the source dates are day first and that the rewrite script failed.

  6. Step 6 of 6

    Two exits

    The actor resumes from point 22 with the memory in view and finishes the load. A run that reaches 40 steps without finishing leaves as not completed. After 3 rollbacks, nothing more is restored.

What each part does
Task
A long task to carry out in a workspace that the harness can save and restore, with a plan if there is one.
Actor
Chooses one action at a time, asks for a review when its path looks lost, or declares the task complete.
Reflection memory
What abandoned paths taught: facts about the environment, routes already tried and why the last one failed.
Workspace
The controlled environment in which actions run: files, a container or a test database.
Checkpoint store
One entry per step, saved before the action runs: the workspace and the actor's context, kept as a pair.
Review due?
Plain code. Counts steps and rollbacks, and sends the run to a review at fixed intervals or on request.
Reviewer
Judges whether the path can still succeed. If not, names the cause, picks the restore point and writes the lesson.
Result
The actor's final answer with the log of the steps on the path that was kept, and the rollbacks made.
Not completed
The report of a run that used all its steps, with the reflection memory and the state of the workspace.
  • Reflection memory → Actor: lessons of abandoned paths
  • Actor → Workspace: next action
  • Actor → Review due?: asks for a review
  • Actor → Result: task complete
  • Workspace → Checkpoint store: files and context before each action
  • Workspace → Review due?: observation
  • Review due? → Actor: no review due
  • Review due? → Reviewer: review due, rollbacks left
  • Review due? → Not completed: step budget used up
  • Checkpoint store → Reviewer: list of restore points
  • Reviewer → Reflection memory: lesson of the abandoned stretch
  • Checkpoint store → Workspace: restores the files
  • Checkpoint store → Actor: restores the context
  • Reviewer → Actor: continue, or resume from the point

Where it connects

Entry
task
TaskPlan

A long task carried out in a workspace the harness can save and restore. Actions with effects outside that workspace are not available to the actor. A plan, if given, guides the steps.

Exit
result
AnswerOutcome

When: The actor declares the task complete within the step budget.

The final answer, the log of the steps on the path that was kept, the number of rollbacks and the reflection memory as it stood at the end.

Exit
failed
Verdict

When: The step budget is used up before the actor declares the task complete.

A statement that the task was not completed, with the last failure analysis, the reflection memory, the rollbacks made and the current state of the workspace.

Working memory for one run
checkpoints
World state

One entry per step with the saved workspace and the actor's context at that step. Entries after a restore point are dropped when the run returns to it. Discarded at the end.

Working memory for one run
memory
Knowledge

The fixed goal, facts observed about the environment, routes tried on abandoned paths, and the analysis of the latest failure. Never restored with a checkpoint.

4

What do I ask my assistant to set up?

The agents to launch

Actor

Carry out the task one action at a time in the workspace. Read the reflection memory first: it holds what earlier, abandoned paths taught. Check any fact it marks as uncertain before relying on it. If the same failure comes back, or your path cannot reach the goal, ask for a review instead of patching further. Say when the task is complete.

Sees: The task, the reflection memory, the log of the current path and the number of rollbacks left. Not the steps that were rolled back.

Reviewer

Decide whether the current path can still reach the goal. Repairing in place is the default. If the path is lost, name the cause, then pick the latest restore point at which that cause is not yet present. Write what the abandoned stretch taught: facts about the environment, the route tried, and why it failed. Write them as past events, not as the current state.

Sees: The task, the log of the current path, the numbered restore points and the reflection memory. It takes no action in the workspace.

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 "Recoverable Execution" 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]

# Recoverable Execution
Go back to a saved point, restore the world, keep the lesson.
Input: the task above. It must provide: A long task carried out in a workspace the harness can save and restore. Actions with effects outside that workspace are not available to the actor. A plan, if given, guides the steps. If something essential is missing, ask for it before starting.

Agents to launch:
- Actor: Carry out the task one action at a time in the workspace. Read the reflection memory first: it holds what earlier, abandoned paths taught. Check any fact it marks as uncertain before relying on it. If the same failure comes back, or your path cannot reach the goal, ask for a review instead of patching further. Say when the task is complete.
  Context for this agent: The task, the reflection memory, the log of the current path and the number of rollbacks left. Not the steps that were rolled back.
- Reviewer: Decide whether the current path can still reach the goal. Repairing in place is the default. If the path is lost, name the cause, then pick the latest restore point at which that cause is not yet present. Write what the abandoned stretch taught: facts about the environment, the route tried, and why it failed. Write them as past events, not as the current state.
  Context for this agent: The task, the log of the current path, the numbered restore points and the reflection memory. It takes no action in the workspace.

Procedure:
1. Put the work in a place you can save and restore as a whole, such as a folder under version control or a container. Remove every tool that acts outside it.
2. Before each action of the actor, save the workspace and the actor's context under the same step number.
3. Keep the reflection memory outside the checkpoints. Start it with the goal of the task and nothing else.
4. Call the reviewer when the actor asks for a review, or 6 steps after the last one, as long as fewer than 3 rollbacks were made.
5. On a rollback, restore the workspace and the context of the chosen point and drop the later checkpoints. Add the reviewer's facts and route to the memory and replace its failure analysis.
6. Resume the actor from the restored context, with the updated memory placed ahead of it.
7. When the actor declares the task complete, release the result. At the step limit, release the failure report.

Stop rule: Stop when the actor declares the task complete, or after 40 steps, and then report the task as not completed. After 3 rollbacks, restore nothing more and let the run continue on its path.

Exits:
- `result`, when: The actor declares the task complete within the step budget. Deliver: The final answer, the log of the steps on the path that was kept, the number of rollbacks and the reflection memory as it stood at the end.
- `failed`, when: The step budget is used up before the actor declares the task complete. Deliver: A statement that the task was not completed, with the last failure analysis, the reflection memory, the rollbacks made and the current state of the workspace.

# Final deliverable
Either the answer with the log of the kept path and the rollbacks made, or a report marked not completed with the last failure analysis and the memory.

The same thing in code

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

from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel

MAX_STEPS, MAX_ROLLBACKS, REVIEW_EVERY = 40, 3, 6
WORKSPACE: dict[str, str] = {}  # the controlled environment, path -> contents: plug in a folder or a container
model = init_chat_model("anthropic:claude-sonnet-5-5")

ACTOR = ("Carry out the task one action at a time. Read the reflection memory first and re-check any fact it marks "
         "as uncertain. If the same failure comes back or your path cannot reach the goal, ask for a review "
         "instead of patching further. Finish only when the task is complete.")
REVIEWER = ("Decide whether the current path can still reach the goal. Repair in place is the default. If the path "
            "is lost, name the cause and pick the latest restore point at which the cause is not yet present. "
            "Write what the abandoned stretch taught as past events, not as the current state.")


class Step(BaseModel):
    action: Literal["act", "review", "finish"]
    command: str  # act: the command to run in the workspace
    text: str  # finish: the answer; review: why the path looks lost


class Review(BaseModel):
    rollback: bool
    checkpoint: int  # rollback: number of the restore point
    diagnosis: str  # why the abandoned stretch failed
    facts: list[str]  # what it showed about the environment
    route: str  # one line on the route that was tried


class State(TypedDict):
    task: str
    trace: list[str]  # the actor's context: the log of the current path
    checkpoints: list[tuple[dict[str, str], list[str]]]  # (workspace, context) saved before each action
    memory: dict  # kept outside the checkpoints, so a restore never erases it
    steps: int
    since_review: int
    rollbacks: int
    wants_review: bool
    answer: str


def execute(command: str) -> str:
    # plug in the real execution inside the workspace; it must not reach anything outside it
    return "stub: nothing executed"


def view(state: State) -> str:
    log = "\n".join(state["trace"]) or "none"
    left = MAX_ROLLBACKS - state["rollbacks"]
    return f"Task: {state['task']}\nReflection memory: {state['memory']}\nRollbacks left: {left}\nLog of this path:\n{log}"


async def actor(state: State) -> dict:
    raw = await model.with_structured_output(Step).ainvoke([SystemMessage(ACTOR), HumanMessage(view(state))])
    step = Step.model_validate(raw)
    if step.action == "finish":
        return {"answer": step.text}
    if step.action == "review":
        return {"wants_review": True, "steps": state["steps"] + 1}
    # the harness saves the workspace and the context as a pair, before the action runs
    saved = state["checkpoints"] + [(dict(WORKSPACE), list(state["trace"]))]
    line = f"{step.command} -> {execute(step.command)}"
    return {"checkpoints": saved, "trace": state["trace"] + [line], "steps": state["steps"] + 1,
            "since_review": state["since_review"] + 1, "wants_review": False}


def gate(state: State) -> str:  # plain code: counts steps and rollbacks
    if state["answer"] or state["steps"] >= MAX_STEPS:
        return END
    due = state["wants_review"] or state["since_review"] >= REVIEW_EVERY
    return "reviewer" if due and state["rollbacks"] < MAX_ROLLBACKS else "actor"


async def reviewer(state: State) -> dict:
    points = "\n".join(f"{i}: before `{line}`" for i, line in enumerate(state["trace"]))
    prompt = f"{view(state)}\n\nRestore points:\n{points}"
    raw = await model.with_structured_output(Review).ainvoke([SystemMessage(REVIEWER), HumanMessage(prompt)])
    review = Review.model_validate(raw)
    if not review.rollback or not 0 <= review.checkpoint < len(state["checkpoints"]):
        return {"since_review": 0, "wants_review": False}  # continue on the current path
    files, context = state["checkpoints"][review.checkpoint]
    WORKSPACE.clear()
    WORKSPACE.update(files)  # the world goes back
    old = state["memory"]
    memory = {"goal": old["goal"], "facts": old["facts"] + review.facts,
              "routes_tried": old["routes_tried"] + [review.route], "last_failure": review.diagnosis}
    return {"trace": list(context), "checkpoints": state["checkpoints"][:review.checkpoint], "memory": memory,
            "rollbacks": state["rollbacks"] + 1, "since_review": 0, "wants_review": False}


builder = StateGraph(State)
builder.add_node("actor", actor)
builder.add_node("reviewer", reviewer)
builder.add_edge(START, "actor")
builder.add_conditional_edges("actor", gate, ["actor", "reviewer", END])
builder.add_edge("reviewer", "actor")
graph = builder.compile()


async def run(task: str) -> dict:
    memory = {"goal": task, "facts": [], "routes_tried": [], "last_failure": ""}
    s = await graph.ainvoke({"task": task, "trace": [], "checkpoints": [], "memory": memory, "steps": 0,
                             "since_review": 0, "rollbacks": 0, "wants_review": False, "answer": ""},
                            {"recursion_limit": 120})
    status = "result" if s["answer"] else "failed"
    return {"status": status, "answer": s["answer"], "log": s["trace"], "rollbacks": s["rollbacks"], "memory": s["memory"]}

The checkpoint store here is the list in the state, not LangGraph's own checkpointer, which saves graph state but not your files. Replace WORKSPACE and execute with a real sandbox.

Claude Agent SDK, python, package claude-agent-sdk
from typing import Literal, TypeVar

from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
from pydantic import BaseModel

MAX_STEPS, MAX_ROLLBACKS, REVIEW_EVERY = 40, 3, 6
WORKSPACE: dict[str, str] = {}  # the controlled environment, path -> contents: plug in a folder or a container

ACTOR = ("Carry out the task one action at a time. Read the reflection memory first and re-check any fact it marks "
         "as uncertain. If the same failure comes back or your path cannot reach the goal, ask for a review "
         "instead of patching further. Finish only when the task is complete.")
REVIEWER = ("Decide whether the current path can still reach the goal. Repair in place is the default. If the path "
            "is lost, name the cause and pick the latest restore point at which the cause is not yet present. "
            "Write what the abandoned stretch taught as past events, not as the current state.")


class Step(BaseModel):
    action: Literal["act", "review", "finish"]
    command: str  # act: the command to run in the workspace
    text: str  # finish: the answer; review: why the path looks lost


class Review(BaseModel):
    rollback: bool
    checkpoint: int  # rollback: number of the restore point
    diagnosis: str  # why the abandoned stretch failed
    facts: list[str]  # what it showed about the environment
    route: str  # one line on the route that was tried


M = TypeVar("M", bound=BaseModel)


async def ask(system: str, prompt: str, schema: type[M]) -> M:
    # no tools: the model proposes, and the harness runs the command so that it can save a checkpoint first
    options = ClaudeAgentOptions(
        system_prompt=system, allowed_tools=[],
        output_format={"type": "json_schema", "schema": schema.model_json_schema()},
    )
    async for msg in query(prompt=prompt, options=options):
        if isinstance(msg, ResultMessage):
            return schema.model_validate(msg.structured_output)
    raise RuntimeError("no result")


def execute(command: str) -> str:
    # plug in the real execution inside the workspace; it must not reach anything outside it
    return "stub: nothing executed"


async def run(task: str) -> dict:
    trace: list[str] = []  # the actor's context: the log of the current path
    checkpoints: list[tuple[dict[str, str], list[str]]] = []  # (workspace, context) saved before each action
    memory = {"goal": task, "facts": [], "routes_tried": [], "last_failure": ""}  # outside the checkpoints
    rollbacks, since_review = 0, 0
    for _ in range(MAX_STEPS):
        log = "\n".join(trace) or "none"
        view = (f"Task: {task}\nReflection memory: {memory}\nRollbacks left: {MAX_ROLLBACKS - rollbacks}\n"
                f"Log of this path:\n{log}")
        step = await ask(ACTOR, view, Step)
        if step.action == "finish":
            return {"status": "result", "answer": step.text, "log": trace, "rollbacks": rollbacks, "memory": memory}
        if step.action == "act":
            checkpoints.append((dict(WORKSPACE), list(trace)))  # the pair, before the action runs
            trace.append(f"{step.command} -> {execute(step.command)}")
            since_review += 1
        due = step.action == "review" or since_review >= REVIEW_EVERY
        if not due or rollbacks >= MAX_ROLLBACKS:  # the gate: plain code
            continue
        since_review = 0
        points = "\n".join(f"{i}: before `{line}`" for i, line in enumerate(trace))
        review = await ask(REVIEWER, f"{view}\n\nRestore points:\n{points}", Review)
        if not review.rollback or not 0 <= review.checkpoint < len(checkpoints):
            continue  # continue on the current path
        files, context = checkpoints[review.checkpoint]
        WORKSPACE.clear()
        WORKSPACE.update(files)  # the world goes back
        trace = list(context)  # and so does the context
        del checkpoints[review.checkpoint:]
        memory["facts"] += review.facts  # the lesson stays
        memory["routes_tried"].append(review.route)
        memory["last_failure"] = review.diagnosis
        rollbacks += 1
    return {"status": "failed", "answer": None, "log": trace, "rollbacks": rollbacks, "memory": memory}

The model only proposes commands here, so the harness can save before each one. With the SDK's own file tools, snapshot the working directory in your loop, for example one commit per step.

OpenAI Agents SDK, python, package openai-agents
from typing import Literal

from agents import Agent, Runner
from pydantic import BaseModel

MAX_STEPS, MAX_ROLLBACKS, REVIEW_EVERY = 40, 3, 6
WORKSPACE: dict[str, str] = {}  # the controlled environment, path -> contents: plug in a folder or a container


class Step(BaseModel):
    action: Literal["act", "review", "finish"]
    command: str  # act: the command to run in the workspace
    text: str  # finish: the answer; review: why the path looks lost


class Review(BaseModel):
    rollback: bool
    checkpoint: int  # rollback: number of the restore point
    diagnosis: str  # why the abandoned stretch failed
    facts: list[str]  # what it showed about the environment
    route: str  # one line on the route that was tried


actor = Agent(
    name="Actor",
    instructions="Carry out the task one action at a time. Read the reflection memory first and re-check any fact "
                 "it marks as uncertain. If the same failure comes back or your path cannot reach the goal, ask "
                 "for a review instead of patching further. Finish only when the task is complete.",
    output_type=Step)
reviewer = Agent(
    name="Reviewer",
    instructions="Decide whether the current path can still reach the goal. Repair in place is the default. If "
                 "the path is lost, name the cause and pick the latest restore point at which the cause is not "
                 "yet present. Write what the abandoned stretch taught as past events, not as the current state.",
    output_type=Review)


def execute(command: str) -> str:
    # plug in the real execution inside the workspace; it must not reach anything outside it
    return "stub: nothing executed"


async def run(task: str) -> dict:
    trace: list[str] = []  # the actor's context: the log of the current path
    checkpoints: list[tuple[dict[str, str], list[str]]] = []  # (workspace, context) saved before each action
    memory = {"goal": task, "facts": [], "routes_tried": [], "last_failure": ""}  # outside the checkpoints
    rollbacks, since_review = 0, 0
    for _ in range(MAX_STEPS):
        log = "\n".join(trace) or "none"
        view = (f"Task: {task}\nReflection memory: {memory}\nRollbacks left: {MAX_ROLLBACKS - rollbacks}\n"
                f"Log of this path:\n{log}")
        # a fresh run per step: the actor's context is exactly the restored log plus the memory
        step = (await Runner.run(actor, view)).final_output_as(Step)
        if step.action == "finish":
            return {"status": "result", "answer": step.text, "log": trace, "rollbacks": rollbacks, "memory": memory}
        if step.action == "act":
            checkpoints.append((dict(WORKSPACE), list(trace)))  # the pair, before the action runs
            trace.append(f"{step.command} -> {execute(step.command)}")
            since_review += 1
        due = step.action == "review" or since_review >= REVIEW_EVERY
        if not due or rollbacks >= MAX_ROLLBACKS:  # the gate: plain code
            continue
        since_review = 0
        points = "\n".join(f"{i}: before `{line}`" for i, line in enumerate(trace))
        review = (await Runner.run(reviewer, f"{view}\n\nRestore points:\n{points}")).final_output_as(Review)
        if not review.rollback or not 0 <= review.checkpoint < len(checkpoints):
            continue  # continue on the current path
        files, context = checkpoints[review.checkpoint]
        WORKSPACE.clear()
        WORKSPACE.update(files)  # the world goes back
        trace = list(context)  # and so does the context
        del checkpoints[review.checkpoint:]
        memory["facts"] += review.facts  # the lesson stays
        memory["routes_tried"].append(review.route)
        memory["last_failure"] = review.diagnosis
        rollbacks += 1
    return {"status": "failed", "answer": None, "log": trace, "rollbacks": rollbacks, "memory": memory}

Each step is a fresh run on the log, so restoring the context is restoring a list. Replace WORKSPACE and execute with a real sandbox that has no access to the outside.

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

const MAX_STEPS = 40;
const MAX_ROLLBACKS = 3;
const REVIEW_EVERY = 6;
const model = anthropic('claude-sonnet-5-5');
const WORKSPACE = new Map<string, string>(); // the controlled environment: plug in a folder or a container

const ACTOR =
  'Carry out the task one action at a time. Read the reflection memory first and re-check any fact it marks ' +
  'as uncertain. If the same failure comes back or your path cannot reach the goal, ask for a review ' +
  'instead of patching further. Finish only when the task is complete.';
const REVIEWER =
  'Decide whether the current path can still reach the goal. Repair in place is the default. If the path ' +
  'is lost, name the cause and pick the latest restore point at which the cause is not yet present. ' +
  'Write what the abandoned stretch taught as past events, not as the current state.';

const stepSchema = z.object({
  action: z.enum(['act', 'review', 'finish']),
  command: z.string().describe('act: the command to run in the workspace'),
  text: z.string().describe('finish: the answer; review: why the path looks lost'),
});
const reviewSchema = z.object({
  rollback: z.boolean(),
  checkpoint: z.number().describe('rollback: number of the restore point'),
  diagnosis: z.string().describe('why the abandoned stretch failed'),
  facts: z.array(z.string()).describe('what it showed about the environment'),
  route: z.string().describe('one line on the route that was tried'),
});

// plug in the real execution inside the workspace; it must not reach anything outside it
async function execute(_command: string): Promise<string> {
  return 'stub: nothing executed';
}

export async function run(task: string) {
  let trace: string[] = []; // the actor's context: the log of the current path
  const checkpoints: { files: Map<string, string>; context: string[] }[] = []; // saved before each action
  const memory = { goal: task, facts: [] as string[], routesTried: [] as string[], lastFailure: '' }; // kept outside
  let rollbacks = 0;
  let sinceReview = 0;
  for (let n = 0; n < MAX_STEPS; n++) {
    const view =
      `Task: ${task}\nReflection memory: ${JSON.stringify(memory)}\n` +
      `Rollbacks left: ${MAX_ROLLBACKS - rollbacks}\nLog of this path:\n${trace.join('\n') || 'none'}`;
    const { output: step } = await generateText({
      model, instructions: ACTOR, prompt: view, output: Output.object({ schema: stepSchema }),
    });
    if (step.action === 'finish') return { status: 'result', answer: step.text, log: trace, rollbacks, memory };
    if (step.action === 'act') {
      checkpoints.push({ files: new Map(WORKSPACE), context: [...trace] }); // the pair, before the action runs
      trace.push(`${step.command} -> ${await execute(step.command)}`);
      sinceReview++;
    }
    const due = step.action === 'review' || sinceReview >= REVIEW_EVERY;
    if (!due || rollbacks >= MAX_ROLLBACKS) continue; // the gate: plain code
    sinceReview = 0;
    const points = trace.map((line, i) => `${i}: before \`${line}\``).join('\n');
    const { output: review } = await generateText({
      model, instructions: REVIEWER, prompt: `${view}\n\nRestore points:\n${points}`,
      output: Output.object({ schema: reviewSchema }),
    });
    const point = checkpoints[review.checkpoint];
    if (!review.rollback || !point) continue; // continue on the current path
    WORKSPACE.clear();
    point.files.forEach((content, path) => WORKSPACE.set(path, content)); // the world goes back
    trace = [...point.context]; // and so does the context
    checkpoints.length = review.checkpoint;
    memory.facts.push(...review.facts); // the lesson stays
    memory.routesTried.push(review.route);
    memory.lastFailure = review.diagnosis;
    rollbacks++;
  }
  return { status: 'failed', answer: null, log: trace, rollbacks, memory };
}

Each step is a fresh call on the log, so restoring the context is restoring an array. Replace WORKSPACE and execute with a real sandbox that has no access to the outside.

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 memory stored inside the checkpoint is erased by the restore. Keep it apart, or the run repeats the abandoned stretch.
  • A note such as "the table is loaded" is false after a restore. Record what was tried as past events, and mark observations that depended on undone actions.
  • A restore covers only what you saved. A network call or a message sent from inside the workspace stays sent.
  • Going back too little keeps the fault. Ask for the latest point at which the cause is absent, not for the step where the symptom appeared.
  • A reviewer that rolls back at every difficulty makes no progress. Make repair in place the default and cap the rollbacks.

Chain it

Its result can feed

It can take the result of

On a condition

Source