Keep state, deadlines and command routing in a deterministic process manager while an agent supplies a bounded assessment.
Put uncertainty inside one workflow step
A process manager decides which message to send next from the state of an ongoing workflow. Adding an agent does not remove that job. It introduces an uncertain component that may interpret an input, propose a classification or explain a failure. The useful architectural question is where that uncertainty ends. In this guide, the agent proposes an assessment; deterministic code still decides whether an assessment is admissible and what command may follow it.
Consider a synthetic artifact inspection pipeline. A request identifies an immutable artifact digest. A scanner returns structured findings, an agent groups ambiguous diagnostics, a validator checks the proposed classification, and an executor records the accepted disposition. The executor does not install software or change a real system. This deliberately small example lets us inspect message order and authority without pretending to measure a production service.
The Process Manager pattern in Enterprise Integration Patterns describes centralized coordination using intermediate state. Our adaptation keeps that coordination while making the agent an explicitly bounded participant. A workflow does not become an autonomous loop simply because one participant uses a model. If a fixed parser can classify the findings, keep that parser: it costs less, is easier to test and introduces no probabilistic dependency.
Define state before adding an agent
Use states such as received, scanning, awaiting_assessment, awaiting_review, accepted and rejected. Each persisted instance also stores an artifact digest, revision, assessment request identifier and deadline. The digest binds the assessment to the exact input. The revision detects a worker acting on an earlier state. The request identifier distinguishes a retry of an assessment from a new assessment after the artifact changed.
The transition table is an application contract. A scan result is meaningful in scanning, an assessment in awaiting_assessment, and a human decision in awaiting_review. Terminal states reject later commands. Unsupported messages go to a diagnostic queue with their identifiers; silently accepting them makes recovery dependent on arrival order. Parking an early message also needs an explicit replay policy. Marking it permanently consumed would prevent a valid later replay.
Represent the model output as data: classification, referenced finding identifiers and a short explanation. Do not accept arbitrary queue names, executable function names or destination URLs. The process manager translates a valid classification into one of its known commands. It verifies that referenced findings exist, that the artifact digest matches and that the state still expects this assessment. A syntactically valid JSON object is only the first of these checks.
Work through a delayed assessment
Request R17 starts at revision 4 with artifact digest D1. The manager issues assessment request A17 and persists a deadline. At the deadline, a timer message advances the instance to awaiting_review at revision 5. A delayed agent reply for A17 then arrives and recommends acceptance. It was a legitimate response to an earlier request, but it no longer has permission to advance this workflow.
The manager records the late reply as evidence and leaves the instance in awaiting_review. It does not reset the deadline, reopen the old state or make a second acceptance command. A reviewer may use the reply when making a decision, but that is a new transition with its own authorization and revision check. This is why storing only the latest conversation text is insufficient: text does not express which transition remains valid.
Now reverse the order. A17 arrives before the timer and advances the instance to accepted. When the timer arrives, its expected revision no longer matches. It becomes an obsolete timer rather than an instruction to reopen review. Both orders have a clear outcome. The model prompt need not explain race resolution because the model does not own it.
Separate deciding from delivering
A pure transition function takes state and a validated message and returns a next state plus proposed commands. It performs no network calls. This makes the transition replayable and lets tests enumerate unexpected messages without a queue or model. A persistence adapter then checks the expected revision and stores the transition and outgoing command records together.
# Author: Sandeep Belgavi. Illustrative transition core.
def assess(state, message):
if state["phase"] != "awaiting_assessment":
return state, [], "late_or_unexpected"
if message["request_id"] != state["assessment_id"]:
return state, [], "wrong_request"
if message["digest"] != state["digest"]:
return state, [], "wrong_artifact"
decision = message["classification"]
if decision not in {"accept", "reject", "review"}:
decision = "review"
next_state = dict(state, phase=decision,
revision=state["revision"] + 1)
command = {"kind": "record_disposition", "value": decision,
"key": f'{state["id"]}:{next_state["revision"]}'}
return next_state, [command], "applied"The dictionary example omits storage, schema parsing and authenticated identity. Those are required adapters, not implied guarantees. In a database implementation, compare the revision in the update predicate and treat an affected-row count of zero as a conflict. Reload and evaluate the message again. Do not reuse commands calculated from the losing revision.
An outgoing-command table or equivalent transactional mechanism closes the crash window between changing state and arranging delivery. Delivery can still repeat. The receiving adapter therefore recognizes a stable command key. Message deduplication and command idempotency address different repetitions: one incoming message may produce several commands, and the same outgoing command may be transmitted multiple times after a worker failure.
Migrate one boundary at a time
First record the current workflow as a transition table and identify operations that already require deterministic validation. Add correlation identifiers, revisions and durable timers before introducing the model. Then run the agent in a shadow assessment step: collect proposals alongside the existing classifier while the existing implementation continues to decide outcomes.
Use synthetic ambiguous and adversarial findings to test the output contract. Measure disagreement categories and invalid references, not an invented overall intelligence score. If the agent provides useful information, enable it for a narrow subset whose downstream actions remain reversible or require review. Keep an explicit fallback when the model is unavailable or exceeds its deadline.
Version the policy independently from the prompt. A changed prompt may alter assessments while the permitted transition graph remains stable. A changed graph is a workflow migration and may require old instances to finish under their original version. Do not assume a prompt rollback also rolls back persisted workflow state or external effects.
Verify races and recovery explicitly
Test assessment-before-timeout and timeout-before-assessment, duplicate scan results, an unknown classification, a valid classification for the wrong digest, and two workers processing the same revision. Assert commands as well as final state. A test that checks only accepted versus rejected can miss duplicate command delivery.
Inject a crash after the transaction commits but before delivery acknowledgement. On restart, the pending command should be redelivered with the same key. Separately inject a crash before commit; no command should escape. These tests belong at the storage and delivery boundary, while transition unit tests remain fast and offline.
This design has costs: a coordinator needs durable storage, transition migrations and operational ownership. It is excessive for a short pure calculation or an interaction with no durable effects. Where a workflow already has important state transitions, however, adding an agent is a reason to make the boundary clearer. Let the uncertain assessment improve a decision while the application retains the rules that make the decision safe to execute.
Run the example yourself
The synthetic fixtures, expected output and tests behind this guide are in the companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.