@noetaris/harness-testing
v0.5.0
Published
Testing utilities for @noetaris/harness agents
Readme
@noetaris/harness-testing
Testing utilities for @noetaris/harness agents. Provides isolated step execution, route testing, and an Observer test double — all designed for unit and integration tests of individual steps without spinning up the full agent loop.
Overview
runStep— executes a single named step in isolation with a syntheticctx, capturing state updates, interrupts, and errors in a typed resultrunRoute— invokes a step'sroutefunction directly with a synthetic state snapshotMockObserver— records all harness lifecycle calls (onRunStart,onStepEnd,onEvent,onStepSettled, …) for assertion, including the path an agent took and each step's signal, next step and update
Installation
pnpm add -D @noetaris/harness-testingPeer dependency:
pnpm add @noetaris/harness # 0.12.0 or laterQuick Start
import { runStep, MockObserver } from '@noetaris/harness-testing'
// test a step in isolation
const result = await runStep(harness, 'fetchData', {
slots: { llm: mockLlm },
state: { query: 'hello' },
})
expect(result.state).toEqual({ response: 'world' })
expect(result.interrupted).toBeNull()
expect(result.error).toBeNull()
// observe a full run
const obs = new MockObserver()
await agent.run({}, { observer: obs })
expect(obs.calls.onStepEnd).toHaveLength(3)
expect(obs.events('llm.response')).toHaveLength(1)API Reference
runStep
runStep<S, Ctx>(
harness: Harness<Ctx, S, any, any>,
stepName: string,
options: RunStepOptions<S, Ctx>,
): Promise<StepResult<S>>Executes one step from the harness loop definition in isolation. Always resolves — interrupts and errors are captured in StepResult rather than thrown.
The synthetic ctx has the same fields as a real step ctx. ctx.within(type, payload, fn) just runs fn, because there is no observer: a step that calls it, or runTool from @noetaris/harness-types, runs under runStep, and a rejection or throw from fn reaches the step as it would in a run.
Throws StepNotFoundError if stepName doesn't exist in the loop, or NoRunFunctionError if the step has no run function (decision-only steps).
RunStepOptions<S, Ctx>
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| slots | Ctx | — | User-defined context slots passed as the step's ctx argument. |
| state | Partial<S> | — | Initial state snapshot passed as the step's first argument. |
| interruptResponses | Record<string, unknown> | — | Pre-loaded interrupt responses keyed by interrupt ID. When a key is present the interrupt is answered immediately (replay mode). When absent the interrupt is captured and execution stops (pause mode). |
| sessionId | string | "test-session" | Injected as ctx.sessionId. |
| agentId | string | "test-agent" | Injected as ctx.agentId. |
| runId | string | crypto.randomUUID() | Injected as ctx.runId. |
| signal | AbortSignal | never-aborts signal | Injected as ctx.signal. |
StepResult<S>
Exactly one of state, interrupted, or error is non-null per call.
| Field | Type | Description |
|-------|------|-------------|
| state | Partial<S> \| null | State update returned by the step. Null if interrupted or errored. |
| interrupted | { interruptId: string; prompt: unknown } \| null | Populated when the step called ctx.interrupt() without a matching interruptResponses entry. |
| error | Error \| null | Error thrown by the step (non-interrupt errors only). |
| events | Array<{ name: string; payload: unknown }> | All events emitted via ctx.emit() during the step, in call order — including the tool.call and tool.result events that runTool emits. |
Examples
Happy path:
const result = await runStep(harness, 'classify', {
slots: { llm: mockLlm },
state: { input: 'hello world' },
})
expect(result.state?.label).toBe('greeting')
expect(result.events).toEqual([{ name: 'classify.done', payload: { label: 'greeting' } }])Interrupt — pause mode (no pre-loaded response):
const result = await runStep(harness, 'confirmAction', {
slots: { llm: mockLlm },
state: { action: 'delete' },
})
expect(result.interrupted).toEqual({
interruptId: 'confirm-delete',
prompt: { message: 'Are you sure?' },
})Interrupt — replay mode (pre-loaded response):
const result = await runStep(harness, 'confirmAction', {
slots: { llm: mockLlm },
state: { action: 'delete' },
interruptResponses: { 'confirm-delete': true },
})
expect(result.state?.confirmed).toBe(true)A step that calls tools with runTool:
const result = await runStep(harness, 'act', {
slots: {},
state: { toolCalls: [{ id: 't1', name: 'search', input: { q: 'x' } }] },
})
expect(result.state).toEqual({ outputs: ['found search'] })
expect(result.events).toEqual([
{ name: 'tool.call', payload: { toolName: 'search', toolCallId: 't1' } },
{ name: 'tool.result', payload: { toolName: 'search', toolCallId: 't1', durationMs: expect.any(Number) } },
])Error capture:
const result = await runStep(harness, 'riskyStep', {
slots: { llm: failingLlm },
state: {},
})
expect(result.error?.message).toMatch('upstream failed')runRoute
runRoute<S, Ctx>(
harness: Harness<Ctx, S, any, any>,
stepName: string,
options: RunRouteOptions<S>,
): stringInvokes a step's route function synchronously with a synthetic state snapshot. Returns the next step name.
Throws StepNotFoundError if stepName doesn't exist, or NoRouteFunctionError if the step has no route function.
RunRouteOptions<S>
| Field | Type | Description |
|-------|------|-------------|
| state | Partial<S> | State snapshot passed to the route function. |
Example
const next = runRoute(harness, 'decide', {
state: { score: 0.9 },
})
expect(next).toBe('approve')
const next2 = runRoute(harness, 'decide', {
state: { score: 0.1 },
})
expect(next2).toBe('reject')MockObserver
A test double implementing the harness Observer interface. Records every lifecycle call for assertion.
const obs = new MockObserver()
await agent.run({}, { observer: obs })
obs.calls.onRunStart // OnRunStartCall[]
obs.calls.onRunEnd // OnRunEndCall[] — event.error is present when the run ended with an error
obs.calls.onStepStart // OnStepStartCall[]
obs.calls.onStepEnd // OnStepEndCall[]
obs.calls.onStepError // OnStepErrorCall[]
obs.calls.onInterrupt // OnInterruptCall[]
obs.calls.onEvent // OnEventCall[]
obs.calls.onStepSettled // OnStepSettledCall[] — one per step: outcome, update, signal, next, …All arrays are always present (never null) even if no calls were made.
onStepSettled records keep event.update as a copy taken when the step settled, so a later step that changes state in place does not change it. Each top-level key is copied with structuredClone; a key whose value can't be cloned (a function, for example) keeps its reference. Compare updates with toEqual, not toBe; class instances come back as plain objects. Every other field is kept as the harness passed it.
obs.settled(branchPath?): OnStepSettledCall[]
Returns the onStepSettled records of the steps that ran in one scope, in call order: the top level by default ([], fork nodes included), or the fork branch named by branchPath (outermost branch first). The match is exact — settled(['x']) does not include the steps of a fork nested inside branch x. Fork branches run concurrently, so steps of different branches can interleave in calls.onStepSettled; within one scope the order is fixed.
// a → b → c
await agent.run({}, { observer: obs })
expect(obs.settled().map(c => c.ctx.stepName)).toEqual(['a', 'b', 'c'])
expect(obs.settled()[0].event.signal).toBe('go')
expect(obs.settled()[0].event.next).toEqual({ kind: 'step', name: 'b' })
expect(obs.settled()[0].event.update).toEqual({ a: 1 })
// prep → fork fan [x: sx1 → sx2, y: sy1 → sy2] → merge
expect(obs.settled().map(c => c.ctx.stepName)).toEqual(['prep', 'fan', 'merge'])
expect(obs.settled(['x']).map(c => c.ctx.stepName)).toEqual(['sx1', 'sx2'])
expect(obs.settled(['x']).map(c => c.event.update)).toEqual([{ xs: ['sx1'] }, { xs: ['sx1', 'sx2'] }])The records span every run the observer saw (a resumed run included); ctx.runId tells the runs apart.
obs.events(name): unknown[]
Filters onEvent records by name and returns the payload values in call order.
const payloads = obs.events('llm.response')
expect(payloads).toHaveLength(1)
expect(payloads[0]).toMatchObject({ model: 'claude-sonnet-4-6' })obs.reset(): void
Clears all recorded calls. Useful when reusing the same observer across multiple agent.run() calls in one test.
await agent.run({}, { observer: obs })
obs.reset()
await agent.run({}, { observer: obs })
expect(obs.calls.onRunStart).toHaveLength(1) // only the second runError Classes
StepNotFoundError
Thrown by runStep and runRoute when the step name does not exist in the loop definition.
NoRunFunctionError
Thrown by runStep when the named step has no run function. This happens for decision-only steps that only define a route function — test their routing logic with runRoute instead.
NoRouteFunctionError
Thrown by runRoute when the named step has no route function.
License
MIT
