Test agentic programs with Experimental.Test
Experimental.
Experimental.Testneeds{ "vibe": { "experimental": ["builtins"] } }intsconfig.jsonorvibe.config.json. Both files take the same"vibe"object. Without it, the compiler reportsEK3013. A release can change or remove it.
Experimental.Test holds test doubles and assertions for programs that call models, run commands and execute durable workflows. Each double is a layer (a value that supplies services to a program), so a test provides it in place of the production layer and changes no line of the program. Use the module when a test must run with no API key, no network and the same result on every machine. Tests stay @effect/vitest tests. The design is VIP-71.
schema Label { type: "bug" | "feature" | "question" | "chore" }
const reply = { type: "text", text: `{"type":"bug"}` }
const recorded = { calls: [{ request: { prompt: "Label this issue: Crash on start" }, response: [reply] }] }
effect function label(title: string) {
const reply = try LanguageModel.generateObject({ prompt: `Label this issue: ${title}`, schema: Label })
return reply.value
}
export effect function labelCrash() {
provide Experimental.Test.replay(recorded) {
const result = try label("Crash on start")
return [result.type, (try Experimental.Test.unconsumed).length]
}
}
// Run in an effect function: try Console.log(try labelCrash())
// Output: [ 'bug', 0 ]Experimental.Test.replay(recorded) is a LanguageModel that answers from the recording and never calls a provider. label asks through whatever LanguageModel is in scope, so it does not know about the test. Experimental.Test.unconsumed lists the recorded calls that the run has not used. Here the list is empty.
Exports
The following table lists the doubles, assertions and suites.
| Export | Kind | What it does |
|---|---|---|
replay(fixture) | Layer | Provides a LanguageModel that answers from a recording |
unconsumed | Effect | Lists the recorded calls a replay or record layer has not used |
record(path, { live }) | Layer | Replays the file at path, sends a miss to the live model, and appends the answer |
decisions(fixture) | Layer | Provides a DecisionModel that answers from a recording |
modelServer({ fixture }) | Layer | Serves a recording as POST /v1/chat/completions on an HttpServer |
host({ files, commands }) | Layer | Provides FileSystem, Path and ChildProcessSpawner from fixed files and scripted commands |
durable | Layer | Provides a durable engine over a fresh in-memory store |
restartable | Layer | Provides a durable engine that crash can stop and restart over the same store |
crash | Effect | Stops the restartable engine as a killed process stops |
journal(run) | Effect | Reads a run's journal and gives assertions over it |
divergence(runA, runB) | Effect | Finds the first difference between two runs' journals |
conformance.engine() | Values | Returns nine cases that certify a workflow engine |
Experimental.Test also exports four members that this guide does not walk through:
| Member | Kind | What it does |
|---|---|---|
recordDecisions(fixture, { live }) | Layer | Answers a decision call from the recording when one matches, and otherwise asks the live model and appends the settled answer to the file |
plan(Workflow, ...args) | Effect | Builds the plan of a workflow for its arguments and gives assertions over its nodes, edges and keys. Nothing runs. |
poisoned(effect) | Effect | Runs an Effect with no services, so a body that passes under it does not depend on the services its caller provides |
conformance.host() | Values | Returns ten cases that certify a host: its file system, its paths and its processes |
Script a language model
A fixture is JSON, usually a file beside the test. Each entry of calls is one model call. The following table lists its fields.
| Field | Holds |
|---|---|
request.prompt | The prompt: a string, or messages in their encoded form |
request.tools, request.responseFormat, request.toolChoice | Optional. Each one is compared only when present |
response | The encoded response parts for generateText and generateObject, such as { "type": "text", "text": "..." } |
stream | The encoded stream parts for streamText, such as text-delta |
failure | An encoded AiError that the call fails with, such as a recorded rate limit |
Each recorded call is claimed once, so two equal requests need two recordings. A request with no matching recording is a defect: the fiber dies with Experimental.Test.UnrecordedCall, and no network call happens. Matching ignores the model ID, so a recording made with one model replays under another. A malformed fixture is also a defect: building the layer dies with Experimental.Test.InvalidFixture.
Record a fixture
To make or refresh a recording, switch the test from replay to record and name the live model. record needs Effect's FileSystem. This sample writes to a temporary directory via NodeFileSystem.layer and supplies a scripted "live" model, so it runs offline.
import { NodeFileSystem } from "@effect/platform-node"
const live = Experimental.Test.replay({ calls: [{ request: { prompt: "Say hi" }, response: [{ type: "text", text: "hi" }] }] })
export effect function refresh() {
provide NodeFileSystem.layer {
return try scoped(effect {
const fs = try FileSystem.FileSystem
const dir = try fs.makeTempDirectoryScoped()
const fixture = `${dir}/hi.json`
try fs.writeFileString(fixture, `{"calls":[]}`)
provide Experimental.Test.record(fixture, { live }) {
const reply = try LanguageModel.generateText({ prompt: "Say hi" })
const file = try fs.readFileString(fixture)
return [reply.text, file.includes(`"content": "Say hi"`), file.includes(`"text": "hi"`)]
}
})
}
}
// Run in an effect function: try Console.log(try refresh())
// Output: [ 'hi', true, true ]The file did not answer the request, so record asked the live model and appended the call before the caller saw the answer. In a real test, live is a provider's layer and the fixture lives in your repository. record builds the live layer at the first miss, so a complete recording runs with no key. It writes nothing for an interrupted call or a defect. A call that holds a credential dies with Experimental.Test.CredentialInRecording and is not written.
Script a decision model
Experimental.Test.decisions(fixture) is the same double for Effect's DecisionModel. Each recorded call holds the encoded input as request.state and the provider's answers by decision name. Each recording is claimed once, and a request that no recording matches dies with Experimental.Test.UnrecordedDecision.
const kind = { _tag: "Classify", label: "bug", probabilities: { bug: 0.9, feature: 0.1 } }
const answers = { calls: [{ request: { state: { title: "Crash on start" } }, response: { answers: { kind } } }] }
const Triage = Decision.make({
input: Schema.Struct({ title: Schema.String }),
decisions: { kind: Decision.classify({ instructions: "What kind of issue is this?", criteria: { bug: null, feature: null } }) }
})
export effect function triageCrash() {
provide Experimental.Test.decisions(answers) {
const response = try DecisionModel.decide(Triage, { input: { title: "Crash on start" } })
return response.answers.kind.label
}
}
// Run in an effect function: try Console.log(try triageCrash())
// Output: bugServe a model to another process
A layer replaces a model inside one process only. For a program that reaches its model over HTTP, such as a coding agent run as a child process, Experimental.Test.modelServer serves the recording. Point the program's OpenAI-compatible base URL at the server.
import { ExperimentalNodeHttpServer } from "vibelang-runtime/experimental/platform-node"
const greeting = { calls: [{ request: { prompt: "hello" }, response: [{ type: "text", text: "hi there" }] }] }
const body = `{"model":"any","messages":[{"role":"user","content":"hello"}]}`
effect function ask(base: string) {
const request = HttpClientRequest.post(`${base}/chat/completions`) |> HttpClientRequest.bodyText(%, body, "application/json")
const response = try HttpClient.execute(request)
return response.status
}
export effect function overHttp() {
const server = Experimental.Test.modelServer({ fixture: greeting })
|> Layer.provideMerge(%, ExperimentalNodeHttpServer.layer({ port: 0 }))
provide server, FetchHttpClient.layer {
const address = (try HttpServer.HttpServer).address
const base = "port" in address ? `http://127.0.0.1:${address.port}/v1` : ""
return [try ask(base), try ask(base)]
}
}
// Run in an effect function: try Console.log(try overHttp())
// Output: [ 200, 501 ]The first request claims the recording. The second finds none and gets 501 with an error of type unrecorded. The server matches as replay does and never compares the model name. It answers a chat.completion, or server-sent chat.completion.chunk events when the request streams.
Describe a machine
Experimental.Test.host({ files, commands }) provides a machine from the test's own description. files maps POSIX paths to text. commands maps a command line, the command and its arguments joined by spaces, to optional stdout, stderr and exitCode. Sandboxes has a sample that scripts a git command with this double. Nothing reaches the operating system. A command that the table does not list fails to spawn with a NotFound PlatformError, and a piped command fails with BadArgument. Each build of the layer starts from its options again.
Crash a durable workflow and assert on its journal
Experimental.Test.durable proves what a workflow runs and journals. It does not prove recovery, because an engine that never restarts never replays. For a crash test, provide Experimental.Test.restartable and run try Experimental.Test.crash.
const done: Array<string> = []
const reached = Deferred.makeUnsafe<void>()
const blocked = { step: 2 }
const Step = Experimental.Durable.task("docs#Step", { payload: { n: Schema.Number }, success: Schema.Number })
const Steps = Experimental.Durable.workflow("docs#Steps", { payload: { count: Schema.Number }, success: Schema.Number })
const perform = (n: number) => {
if (blocked.step !== n) return Effect.sync(() => void done.push(`step ${n}`))
blocked.step = 0
return Effect.andThen(Deferred.succeed(reached, undefined), Effect.never)
}
const StepsLive = Steps.toLayer(effect ({ count }) => {
let total = 0
for (let n = 1; n <= count; n++) total += try Step({ n })
return total
}).pipe(
Layer.provide(Step.toLayer(({ n }) => Effect.as(perform(n), n))),
Layer.provideMerge(Experimental.Test.restartable)
)
export effect function crashMidStep() {
provide StepsLive {
const running = try Effect.forkChild(Steps.execute({ count: 3 }))
try Deferred.await(reached)
try Experimental.Test.crash
const total = try Steps.execute({ count: 3 })
try Fiber.interrupt(running)
const journal = try Experimental.Test.journal(try Steps.executionId({ count: 3 }))
try journal.executedInOrder(["docs#Step/1", "docs#Step/3"])
try all([journal.executed("docs#Step/2"), journal.attempts("docs#Step", 3), journal.terminal("succeeded")])
const starts = journal.steps.map((step) => `${step.step} started ${step.starts}`)
const summary = `${total}: ${done.join(", ")}; ${starts.join(", ")}`
try Steps.execute({ count: 1 })
const differs = try Experimental.Test.divergence(journal.run, try Steps.executionId({ count: 1 }))
return `${summary}\n${Option.isSome(differs) ? `${differs.value.field} differs at ${differs.value.seq}` : "same"}`
}
}
// Run in an effect function: try Console.log(try crashMidStep())
// Output: 6: step 1, step 2, step 3; docs#Step/1 started 1, docs#Step/2 started 2, docs#Step/3 started 1
// Output: payload differs at 1Step 2 blocks before it finishes, and the crash stops it there. The second execute resumes the run on a fresh engine: step 1 returns its recorded result, and step 2 runs again. The journal shows this as two starts of docs#Step/2.
journal(run) takes the run's ID, which is Steps.executionId(payload). It returns steps (each with step, task, attempts, starts and outcome), status, and the assertions in the following table. Each assertion is an Effect that fails with Experimental.Test.JournalMismatch. A name matches a step by its journal name, such as "docs#Step/2", or by its task key, such as "docs#Step", which matches every occurrence.
| Assertion | Holds when |
|---|---|
journal.executed(step) | A step named step finished successfully |
journal.executedInOrder(steps) | The named steps started in this relative order. Other steps can come between |
journal.attempts(step, n) | The named steps were started with n retry attempts in total |
journal.terminal(status) | The run's status is "running", "suspended", "succeeded", "failed" or "interrupted" |
try Experimental.Test.divergence(runA, runB) returns an Option of the first difference between two journals. The value holds the position seq (counted from 1), the field ("entry", "eventType" or "payload"), and the expected and actual values. It does not compare entry times or run IDs.
Certify an engine
Experimental.Test.conformance.engine() returns nine cases that show a workflow engine behaves like the standard one. Each case is a value, { name, run }. run(subject) is an Effect that fails with Experimental.Test.ConformanceViolation. The subject is an Effect that allocates fresh storage and returns the engine's layer over it.
const subject = Effect.sync(() => Experimental.Durable.layerStore(Experimental.Durable.makeMemoryStore()))
export effect function certify() {
const cases = Experimental.Test.conformance.engine()
for (const conformanceCase of cases) try conformanceCase.run(subject)
return `${cases.length} cases passed, from ${cases[0]?.name} to ${cases[8]?.name}`
}
// Run in an effect function: try Console.log(try certify())
// Output: 9 cases passed, from identity/distinct to race/recorded-loserThe replay and race cases restart the engine over its storage, so only an engine that persists runs passes them. Certifying an engine states what each case requires.
Rules and diagnostics
The following table lists the compiler diagnostic and the errors the module raises. A defect stops the fiber and is not part of an Effect's typed failures.
| Code or error | Condition |
|---|---|
EK3013 | A file uses Experimental.Test without the builtins switch |
UnrecordedCall, UnrecordedDecision (defects) | A model or decision request matches no unclaimed recording |
InvalidFixture (defect) | A fixture is malformed |
CredentialInRecording (defect) | record is asked to write a call that holds a credential |
JournalMismatch (failure) | A journal assertion does not hold. It carries message, expected and actual |
ConformanceViolation (failure) | A conformance case does not hold |
Related pages
- Testing agentic programs is the long form of this page.
- Durable workflows and Durable tasks and workflows cover the engine these tests crash.
- Sandboxes covers machines that run real or interpreted commands, and Fuzzing covers generated inputs.
- Building agents covers the programs these doubles test.