loop-to-machine
Convert agent code to a machine
You replace the control flow of working agent code with a machine, and show where it behaves like the old code and where it differs on purpose. Model calls, tools, and retry code move across unchanged.
inventory → pin the baseline → environment → (policy) → runner → proofs → parity → hand back
Default track: wrap first, carve per commit
For an async workflow (not a hand-rolled loop you are asked to replace wholesale), start here, and use the sections below for each carved phase.
- Step 0: wrap and record. Move every side effect behind one
effectsobject of async functions (the only edit to the old code). ThenwrapWorkflow({ id, effects, run: (input, effects) => old(input, effects) })from@statelyai/agent. Pin the baseline withcheckParity(@statelyai/agent/testing):{ scenarios, effects: (s) => fakes, before: old, after: (input, fx) => step0.run(input, { effects: fx }) }; every rowequivalent. Ship it: inspection, traces, the event log,signal, a recorded baseline. - Carve one phase per commit. One phase becomes states (§3); the rest stays the old helper, invoked as a
createAsyncLogicactor built per run fromeffects. Keep the(input, effects)runner signature with a thirdoptionsargument passed through torunAgent(threadId,store,metadata,onTrace,inspect), so traces and inspection never need a copy of the runner. Move any prompt or warning text the carved phase sends into a versioned request config as you carve it: that file is whatimprove-machinemay later edit. RuncheckParityagainst the old code after each carve. Add the §6 proofs for the carved phase only.
A wrapped workflow is a black box: one state, no mid-function resume, no canReach about its inside. Do not report proofs before the phase is carved. Worked example: examples/strangler-fig. A class whose loop calls its own private model/tool methods: replace those methods on the instance inside run so they call effects (no edit to the class). Effect-TS generators, Redux thunks, LangGraph graphs, closures in DI factories, and step loops inside the model SDK have their own seams: docs/strangler-fig.md. Effects bound to one call's live objects: create the workflow once, pass run(input, { effects }) per call. Scrub generated ids and timestamps: compare.normalize for effect arguments, normalizeOutput for the output, normalizeError for thrown errors.
A phase in the middle of a private method: copy only that phase's lines into the carved actor, list the copied line ranges in a comment, and let checkParity call-args catch drift. When a public per-turn hook exists, replace that method on the instance instead and let the machine decide at that boundary (reference.md).