PTENES
MODULE 1.2

🔄 State, errors, and recovery

Model dependencies, stale state, idempotency, timeouts, cancellation, and recovery.

6

Topics

3h

Load

Integrator

Level

Resilience

Type

0 of 60%
1

Model the journey as states

What it is: Each step states what has already happened, which actions are available, and which transition is valid.

Why learn: Without a state model, the agent may confirm before starting or repeat an effect that has already completed.

Current state starting state Allowed tool observable decision Next action verifiable result

Before modeling

Write the person’s request, the current state, and the evidence that will prove completion.

Starting error

Starting with a function name or a button produces a tool with no clear human purpose.

Predict before opening the code

What information changes the decision? What effect needs to appear in the interface? Answer before implementing.

rascunho -> iniciado -> aguardando_confirmacao -> confirmado
Going deeper: evidence worth keeping

Record the input, previous state, decision made, result, and visible change on the page.

Also include a simulated failure and the observed behavior without WebMCP support.

Key concepts

01

explicit state

02

valid transition

03

precondition

04

effect

2

Separate recoverable and definitive errors

What it is: Recoverable errors indicate a next action; terminal errors end the attempt with a verifiable reason.

Why learn: Classification prevents blind loops and lets the agent explain real alternatives to the user.

QuestionStrong contractWeak contract
When to use it?The description names intent and context.“Does things” or “manages.”
What do you receive?Only the data you need.Generic, unlimited object.
What does it return?Verifiable state and next action.Text without a protocol.
How does it fail?Code, reason, and recovery.Opaque exception.

Do

  • ✓ Use specific verbs.
  • ✓ Delimit inputs.
  • ✓ State the evidence.

Avoid

  • ✗ Mix intentions.
  • ✗ Accept any object.
  • ✗ Hide effects.
return {
  ok: false,
  code: "INSCRICAO_NAO_INICIADA",
  recovery: { tool: "iniciar_inscricao" }
};
Going deeper: evidence worth keeping

Record the input, previous state, decision made, result, and visible change on the page.

Also include a simulated failure and the observed behavior without WebMCP support.

Key concepts

01

stable code

02

actionable message

03

next action

04

honest ending

3

Protect against stale state

What it is: The state used to make a decision can change before execution, especially for job openings, prices, and permissions.

Why learn: Revalidating at the time of the effect prevents a tool from using an old snapshot as current authorization.

1

Observe

Capture state, input, and context before the action.

2

Decide

Validate preconditions and choose the allowed transition.

3

Run

Apply the shared rule and respect cancellation.

4

Prove

Update the interface and return a structured result.

Checkpoint

If step 2 fails, the tool doesn't try to “make it work”: it returns an explicit recovery.

if (input.version !== inscricao.version) {
  throw new ConflictError("Estado mudou; consulte novamente.");
}
Going deeper: evidence worth keeping

Record the input, previous state, decision made, result, and visible change on the page.

Also include a simulated failure and the observed behavior without WebMCP support.

Key concepts

01

revalidation

02

state version

03

conflict

04

new reading

4

Make mutations idempotent

What it is: An idempotency key lets you repeat a request without duplicating a subscription, charge, or submission.

Why learn: Agents, networks, and users can repeat calls; the operation needs to distinguish a retry from a new effect.

REFERENCE CODE

headers: { "Idempotency-Key": executionId }
Input

It is small, documented, and verifiable.

Execution

Reuses the application's actual rule.

Output

Lets you verify the effect and continue.

Read the code as a contract

Highlight where input is validated, where the effect happens, where cancellation arrives, and where the UI is updated.

Going deeper: evidence worth keeping

Record the input, previous state, decision made, result, and visible change on the page.

Also include a simulated failure and the observed behavior without WebMCP support.

Key concepts

01

idempotency key

02

safe retry

03

previous result

04

single effect

5

Cancel and set a time limit

What it is: AbortSignal and timeout end work that has lost relevance or exceeded the operational window.

Why learn: True cancellation preserves resources and prevents the interface from showing success after the person has given up.

Simulated failure

Run the scenario with missing state, invalid input, or unavailable capability.

Expected recovery

The response explains what failed, what remains safe, and which action can continue.

Minimum test matrix

✓ reproducible happy path

✓ actionable invalid input

✓ cancellation ends work

✓ fallback preserves the journey

✓ interface reflects the state

✓ backend maintains authorization

const signal = AbortSignal.any([
  executionSignal,
  AbortSignal.timeout(8000)
]);
Going deeper: evidence worth keeping

Record the input, previous state, decision made, result, and visible change on the page.

Also include a simulated failure and the observed behavior without WebMCP support.

Key concepts

01

AbortSignal

02

timeout

03

visual cleanup

04

canceled result

6

Test recovery end to end

What it is: The integration must prove the happy path, invalid order, retry, cancellation, and concurrent changes.

Why learn: A failure matrix turns resilience into verifiable behavior, not architectural intent.

Synthesis exercise

  1. 1. Explain the problem without using the technology name.
  2. 2. Map the state before and after.
  3. 3. Implement the smallest functional proof.
  4. 4. Trigger a failure and record the recovery.
  5. 5. Deliver code, evidence, and one known limitation.

Module challenge

Implement a multi-step signup that blocks out-of-order calls and returns recovery instructions.

Responsible Integrator criterion

The implementation must work, explain its limits, and preserve the human path when the experimental capability is unavailable.

confirmar antes de iniciar -> recovery: iniciar_inscricao
retry com mesma chave -> mesmo resultado
timeout -> interface volta ao estado estável
Going deeper: evidence worth keeping

Record the input, previous state, decision made, result, and visible change on the page.

Also include a simulated failure and the observed behavior without WebMCP support.

Key concepts

01

scenarios

02

evidence

03

reproduction

04

regression

📦 Module delivery

Implement a multi-step signup that blocks out-of-order calls and returns recovery instructions.

Acceptance criterion

The implementation works with WebMCP support and preserves the manual path when the API is unavailable.

Evidence

Include code, the tested scenario, the observed result, and a known limitation.

Technical sources