Advanced Orchestration Engines ⏱ 11 min read 📁 examples/18_state_machine.mjs

Lesson 22: Verified State Machines and Judges

Enforce 3A code standards in state machines with node verification gates, completion fingerprints, RetryLedger loop prevention, and LLM-as-a-judge validation.

1. Why This Feature Exists

Autonomous loops can enter infinite retry cycles if an agent produces slightly different flawed outputs repeatedly. Fingerprinting and RetryLedgers guarantee that nodes fail fast or pivot intelligently.

2. Key Symbols and Exports

Verification Gates
Every node execution is validated against programmatic checks or an LLM judge before transitioning.
Completion Fingerprinting
Hashes node outputs to detect repetitive unproductive retry loops.
RetryLedger
Tracks per-node retry counts and enforces exponential backoff / hard ceilings on failure.
LLM-as-a-Judge
Evaluates qualitative deliverables against strict rubric.

3. Implementation Walkthrough

import {
    ProviderType,
    resolveProvider,
    initializeClient,
    loadCredentials,
    getDefaultModel,
    StateMachine
} from 'merci-sdk';

const PROVIDER = resolveProvider();
const { client } = await initializeClient({ provider: PROVIDER, options: loadCredentials({ provider: PROVIDER }) });

const machine = new StateMachine({
    client,
    model: getDefaultModel({ provider: PROVIDER }),
    initialState: 'GENERATE_SCHEMA',
    states: {
        GENERATE_SCHEMA: {
            execute: async () => ({ schema: 'type User { id: ID! email: String! }' }),
            verify: async (output, ctx) => {
                // Programmatic + Judge verification
                return output.schema.includes('id: ID!') && output.schema.includes('email: String!');
            },
            maxRetries: 3,
            transitions: [{ target: 'VALIDATE_TYPES' }]
        },
        VALIDATE_TYPES: {
            execute: async (ctx) => ({ valid: true }),
            terminal: true
        }
    }
});

const result = await machine.run();
console.log('Verified Result:', result);

4. Wire and Telemetry Mechanics

The verify hook runs immediately upon node completion. If false, RetryLedger logs attempt, fingerprints payload, and re-executes with corrective feedback.

5. Run the Example

Execute the runnable example directly from the repository root:

node examples/18_state_machine.mjs

Read the full example: examples/18_state_machine.mjs →

Expected Output: Executes verified state machine, demonstrates failure recovery, and verifies final deliverable against strict acceptance tests.