15 / 1825 min read

Operate and Debug the Loop

Production begins where the happy-path demo ends.

Find the first wrong transition

Agent failures cascade. A stale fact produces a flawed plan, which selects the wrong tool, which creates an incorrect artifact, which a generous evaluator accepts. Debugging from the final output invites cosmetic prompt changes. Reconstruct the trajectory and identify the earliest point where observed state diverged from expected state.

Classify the failure by layer: objective, specification, model, context, tool, permission, state, orchestration, environment, evaluation, or delivery. Record the evidence for that classification. The fix should live at the earliest layer capable of preventing recurrence.

Debugging an agent means reconstructing the world it saw, the choices it made, and the side effects that actually occurred.

Capture, replay, and compare

A useful run record contains task and system versions, assembled context references, model configuration, tool calls, observations, handoffs, approvals, timing, cost, errors, artifacts, and final receipts. Redact sensitive values while retaining enough structure to explain behavior.

Replay deterministic components exactly. For stochastic components, rerun against the same case and compare distributions or failure categories rather than expecting identical words. Preserve failed trajectories as regression assets, not embarrassing logs to delete.

Economics of the whole loop

Measure tokens, model calls, tool operations, storage, external API fees, retries, parallelism, verification, and human review. Attribute them to a job class and completed outcome. A workflow with low inference cost can still be expensive if it interrupts experts constantly or produces artifacts nobody trusts.

Latency has a shape. Time to first useful signal, time waiting on tools, time waiting for approval, and time to verified completion affect the experience differently. Stream progress that helps a person decide; do not turn internal chatter into a fake progress feed.

Case file

a duplicate payment after a timeout

An accounts-payable agent submits an approved payment request. The provider times out before returning confirmation. The worker treats the call as failed and retries, creating a second payment. Every prompt was followed; the system still caused harm.

The incident review finds the first wrong transition: the harness represented a missing response as a failed side effect rather than an unknown outcome. The tool lacked an idempotency key, the workflow had no reconcile state, and the retry policy did not distinguish safe reads from unsafe writes.

The repair assigns a stable operation identity before payment, persists the attempt, queries provider state after ambiguous responses, forbids blind retries on money movement, and routes unresolved outcomes to a finance reviewer. The incident becomes a regression simulation.

Decisions made

  1. 01Represent ambiguous external outcomes as unknown, not failed.
  2. 02Make write operations idempotent and bind them to approved action state.
  3. 03Use action-specific retry policies rather than generic resilience.
  4. 04Convert the incident trajectory into a deterministic recovery test.

Production reliability lives in the state and side-effect protocol around the model. Fluent reasoning cannot compensate for unsafe distributed-systems behavior.

The production control plane

Long-running workflows need queues, leases, retries, idempotency, rate limits, timeouts, cancellation, dead-letter handling, budgets, health checks, and graceful degradation. A model loop does not replace these distributed-systems responsibilities.

Assume partial failure. The model may succeed while the tool times out. The external system may complete the action while the client loses the response. One worker may fail after another finishes. Persist state before side effects, use stable operation keys, reconcile uncertain outcomes, and make recovery visible.

Coordination is structured state

Workers coordinate through task identities, dependencies, ownership, artifact locations, current state, budgets, and event histories—not by hoping each reads the same conversation. Status must be backed by executor and heartbeat evidence. Completed work must identify the authoritative artifact.

When plans change, invalidate dependent work explicitly. When workers disagree, preserve both claims and route the conflict to an integration owner or evaluator. Coordination metadata is part of the product because it determines whether people can understand and recover the work.

Knowledge must evolve

Production work reveals outdated documentation, missing examples, ambiguous policies, new failure modes, and better defaults. Create a controlled path for promoting those discoveries into durable knowledge, specifications, tools, and tests.

A worker may propose an update with evidence, but the owning person or policy approves consequential changes. Record what the new entry supersedes, where it applies, when it expires, and which regression case demonstrates the need. Learning without governance becomes drift.

Operating multiple workers

A worker fleet needs capacity limits, priority, fairness, routing health, version visibility, cost allocation, failure isolation, and a way to stop or drain work. Aggregate success can hide one job class, customer, or worker lane deteriorating.

Operate by service-level objectives appropriate to the work: time to verified outcome, dangerous-action rate, recovery success, approval burden, cost per accepted artifact, and user correction rate. Keep a human incident path for consequences the automation cannot safely contain.

Failure mode: the green dashboard

A system can report high completion while users quietly redo the work, dangerous cases are excluded from metrics, or workers mark tasks finished before live verification. Aggregate green is not evidence that the important loops are healthy.

Segment metrics by workflow and failure type. Sample trajectories. Compare internal status with black-box outcomes. Ask domain experts which errors create real burden, then make those categories visible even when the headline number becomes less flattering.

Across the business

What this looks like in other departments

The engineering principle stays the same; the workflow, risk, and proof change with the domain.

Customer support

Debug repeated escalations

Trace source retrieval, account observations, policy interpretation, draft, approval, customer action, and reopen reason to find the first wrong step.

Finance

Operate a close queue

Use idempotent entries, exception ownership, approval state, cutoff times, retry policy, reconciliation checks, and a final signed close receipt.

Marketing

Control production cost

Measure research, generation, revisions, human review, asset creation, publishing, and performance by accepted campaign—not by tokens alone.

Operations

Recover partial fulfillment

Persist each side effect, reconcile uncertain vendor responses, reassign blocked steps, and expose the first missing proof instead of restarting the order.

Technical deep dive

The agent incident protocol

Move from a user-visible failure to a durable repair without losing evidence or fixing the wrong layer.

  1. 01ContainStop risky retries, preserve state, protect affected people and systems, and establish the current external truth.
  2. 02ReconstructJoin task, context, model, tool, approval, event, artifact, cost, and user-outcome evidence into one ordered trajectory.
  3. 03LocalizeIdentify the first wrong transition and classify the owning layer instead of beginning from the final bad output.
  4. 04RepairChange policy, context, tool, state machine, harness, evaluation, or delivery at the layer that can prevent recurrence.
  5. 05RatchetAdd regression coverage, update knowledge, adjust autonomy, document remaining risk, and observe the repair in production.

Reference schema

incident: impact + affected scope + detected_at
trajectory: ordered events + versions + actors + artifacts
first_failure: expected state + observed state + evidence
classification: spec | model | context | tool | state | policy | eval
repair: owner + change + rollback + validation
regression: case + invariant + simulated failure
follow_up: autonomy change + knowledge update + production watch

Try it yourself

Run a failure reconstruction

Choose one agent result that required correction and reconstruct the earliest place the workflow diverged from the expected state.

  1. 1Collect the exact task, system versions, context, tools, and output.
  2. 2Build an ordered timeline of decisions, observations, and side effects.
  3. 3Name the first wrong transition and its owning layer.
  4. 4Write the regression case and harness change that prevent recurrence.

Reusable artifact

Agent incident record

A blameless record that turns a failed trajectory into a system improvement.

Impact: [who or what was affected]
Expected: [intended state and proof]
Observed: [actual state and evidence]
First wrong transition: [event and layer]
Contributing conditions: [context, tool, state, policy]
Containment: [immediate protection]
Repair: [system change and owner]
Regression: [case, invariant, production watch]

Before you move on

Receipt checklist

  • A failed run can be reconstructed across every consequential layer.
  • Costs and latency are attributed to verified outcomes and job classes.
  • Writes use idempotency, action-specific retries, and reconciliation.
  • Incidents create regression cases, knowledge updates, and safer defaults.

Primary sources

Further reading

Home
Book
Blog
Calugaru Labs
GitHub
LinkedIn
Email
Theme