@obversa/runtime is the package you import to write and run a workflow:
the shapes (workflow, pipeline, dag, loop), the steps, the reviews,
the person’s question, run() and the record it writes. It imports no
engine or memory adapter; your program supplies the instances.
Install
@obversa/obversa. The package also installs the
obversa-record command, which prints a run’s record as a page a person
scans: Read a record.
Quickstart
One agent, one job, one run. The engine is a stand-in from the testing module, so the file runs offline:examples/one-agent-job.ts
agentJob makes a step from a prompt and an engine name. run runs it
with the engines you pass and returns the outcome. Run it with
npx tsx one-agent-job.ts:
Output
timeoutMs option of agentJob sets a time limit for each engine call.
The maxMemoryBytes and maxOutputBytes options go to the engine
unchanged. A CLI engine uses them as the memory cap for the processes it
starts (4 GiB by default) and the cap on their output.
Declare a team
workflow(name, { brief, roles, stages }) is the team, in a file: the
brief, the roles named once, the stages in order. Each stage says who does
it, what it writes, who reads it and where a red result goes:
examples/teams/writer-reviewer-pair.ts (excerpt)
stage(name, config) is one step; exactly one of agent, run, panel
or input says what kind. Seats come from the engine plugins:
claude('claude-sonnet-4-5') from @obversa/engine-claude-cli,
codex('gpt-5.6-luna') from @obversa/engine-codex-cli,
opencode(model, { executable }) from @obversa/engine-opencode-cli.
person(question) is a role a person fills. briefFromFile(path) reads a
Markdown file as the brief; its front matter may carry files, the paths
the brief expects written. formatEvent(event, totals?) turns one run
event into the line a person reads, and RunResult.usage is what the run
spent in the shape it takes. Every seat of a reviewedBy panel must report
a different model family from the stage’s writer, or the team is refused
before any model runs. The whole file and a real run are on
A writer and a reviewer.
Build a graph
Underworkflow() sit the shapes: pipeline for stages in order, dag
for a dependency graph, sequence and parallel for the two plain cases,
loop for a body that runs until a condition holds. Each returns a Job
you can run or nest. The steps are fnJob for a function, agentJob for a
prompt to an engine, commandJob for a command whose exit code decides:
examples/feature-team.ts (excerpt)
sendsBackTo, and
each must be a step it depends on. A send-back to a step it does not list
fails the sender with an error that names both steps. The target’s own
refine sets the policy: review({ rounds: 2 }) allows two
refinements, and
review({ judge }) hands the same call to a
judge(). A target with no refine
refuses the send-back. The judge reads the dag’s brief (the brief or ticket text the work
answers) and useCase (what the work is for), the target node’s desc and
gate, and the file the target node names in file. brief and
useCase are optional strings on the dag’s config.
The target’s next run reads the send-back as ctx.lastReview, once. A
writing agentJob that runs again after a send-back and leaves its node’s
file as it was fails: it returned the work unchanged, whatever else it
wrote. With no file, a change to any file in the workspace counts. When a
graph is a loop()’s body, each step’s first run in a round reads the
loop’s last review the same way. A step that fails with an error a retry
cannot fix fails the graph with that error, so a loop around the graph
stops, as it does around the step alone.
A fnJob function returns a full outcome, a one-line summary (a pass) or
nothing (a pass with the label as its summary); a throw is a fail carrying
the error. commandJob passes on exit 0 and otherwise fails with the
output as evidence, and target names the step that owns the fix.
passed(name) and failed(name) are conditions for a node’s when that
read a named dependency’s outcome, so an exit code chooses the branch; the
node failed reads must be optional: true. A node that ran out of
rounds meets failed. isolated(job) runs a step
in its own worktree and branch and lands the change on pass. jobMeta,
copyJobMeta and renderPlan read a job’s declared shape and render it.
Review inside it
reviewPanel runs several reviewers on one attempt and passes on a
threshold; a failing panel returns the findings to target, which runs
again:
examples/feature-team.ts (excerpt)
tournament runs n candidates, each in its own worktree, and a judge
scores the finished ones; the highest lands:
examples/tournament.ts (excerpt)
kickback(to, reason) and revisionRequest(input) build the outcome a
reviewer returns to fail a step with findings aimed at a named stage.
quorum(k, ...conditions) is met when k of its inputs hold. agentCheck
asks an engine a scored question as a condition; confidenceCondition and
minConfidence read a confidence and gate on it. RECORDED_ENGINE_USAGE
is the state key under which a run records which model answered each
engine call, so the review gate compares writers with reviewers by family.
Candidate seats
Where a graph names the seat that does the work (adag() node’s agent, a
pipeline() stage’s agent, each seat in review({ reviewers })), it may
name that seat’s ordered alternatives instead:
examples/seat-candidates.ts (excerpt)
fallbackOn policy, so it also moves to the next candidate when that policy
allows it, as the default does. An abort stops the step at once. An empty
candidates list is refused.
Some failures mean the seat could not answer at all. Each of these runs the
same seat once more, then its next candidate:
- A timeout. The call ran past its time limit.
- A stall. The call sent no engine event (text, thinking, a tool call or
usage) for the step’s
stallMs, anagentJoboption. The runtime stops it. - A login error. The engine reported that its login failed.
- A moved CLI version. The engine’s CLI reports a version other than its pin.
- No exit status. The engine’s process ended with no exit status and no result.
- A process the runtime could not watch. The runtime watches each engine process it starts, so that it can stop every process the call left behind. When that watch fails, the runtime stops the process, and the call gives no result.
seat:route event and the run page
name the seat that could not answer, why, and the candidate that answers
instead.
The record names the move in a seat:route event: the requested identity,
the selected candidate, the failure kind and the reset when one is known.
What actually answered stays on the engine:usage event, so the
recorded-model checks compare the answering model’s family, never the
selection’s. When every candidate is unavailable the step ends on a
QUOTA error, with each skip on the record. The error carries the earliest
reset that a candidate reported or the store holds, so a loop’s onLimit
policy waits for that reset or pauses, as it does for a single model.
Inside a review that is an operational failure, never a verdict.
A run may carry an AvailabilityStore on run({ availability }), and
fileAvailabilityStore(path) is the plain-file default. A billing or quota
failure whose reset is proven, meaning a header or a structured field
stated it rather than text parsed out of an error message, writes
(adapter, provider, model) to the time it resets, and a later run skips
that candidate without a call and records the skip. A failure with no
proven reset writes nothing. A host that learns a reset out of band calls
the store’s markUnavailable itself before the run. A store file that
cannot be read counts as empty with a warning in the record, and a run
with no candidate seats never opens the store. The
seat candidates example
runs one end to end.
The family rule still holds over every reachable candidate: inside a
review, no reviewer may resolve to the model family of another reviewer,
the node’s agent or its fixer, over every candidate either side can
run as, or the graph is refused before any model runs. Two alternatives
inside one seat may share a family.
Ask a person
humanReview(name, { question, input, interaction }) makes a review step
that keeps what you changed, what you wrote and whether you approved.
Use it as a loop’s review. Its response
contains feedback, a composed prompt, and an explicit decision:
changes-requested sends work back; only approved passes. The writer’s
consumeFeedback: true includes the full response on its next turn.
Surfaces shows an interactive example.
interaction names the handler with id, declares responseSchema, and
optionally supplies an async answer(request, signal) function. That
function can open a surface and return its payload. Return undefined if
the person cancels. Without a handler, answer through the run’s stored
callbacks client.
An agentJob can also declare interaction. To ask a question, that agent
returns JSON with an interaction object containing question and input.
The answer’s feedback and prompt return to the same model in a fresh
turn with the saved task context. This asks for input; it does not require
an approval decision. person(question, { interaction }) uses the same
rich response in a workflow input stage.
approval(label, { question, target?, answer? }) is a person’s decision as
a step. Yes passes; no goes to target with the note as the finding, or
fails the step when there’s no target; no answer pauses the run:
examples/approval.ts (excerpt)
createCallbackGate makes a question with
an identity, createCallbackClient holds it for one run,
createStoredCallbackClient keeps it across a process exit,
replayCallbackClient rebuilds pending questions from a history, and
directRouter is the smallest router. createApprovalCallbackGate,
approvalSubjectDigest and resolveApproval bind an approval to the exact
bytes it approves. Callback gates is the guide.
Run it
run(job, options) runs a job from a fresh record and returns a
RunResult: the outcome, the usage, and monitor when the page is on.
Turn the page on and read its address from the record:
examples/monitor.ts (excerpt)
run:start before it dispatches work and one
run:end before it returns, both as LoopEvents to onEvent. Cancelling a
waiting workflow reports the run as aborted and leaves the question in the
record, so a later resume can still answer it. An attempt that runs past
its time budget comes back as a typed outcome, not a hang.
Keep the evidence
writeProofArtifact stores one proof packet addressed by its digest, and
createAcceptedResultRecord, resolveAcceptedResult and
acceptedResultMatches bind a result to the inputs, proof, graph and
workspace it was judged on:
examples/proof-bound-approval.ts (excerpt)
createProofCache shares declared read-only evidence between workers.
Proof-bound acceptance and approval is the
guide.
Store and execute
For hosts and for shapes of your own:compileGraph validates a definition
against a graph type, resolveGraphPlan freezes what the run may use,
persistRunDefinition stores it, and createGraphExecutor runs it one
recorded decision at a time:
examples/custom-graph.ts (excerpt)
dagGraphType, convergence and teamGraphType are the forms that ship.
loadRunDefinition reads a stored run back; readRunPreflight and
interruptRunPreflight read and close a run’s engine checks;
validateDomainEventId checks an event id before a resume.
createLocalRunStorage from @obversa/runtime/storage/local is the
on-disk event and artifact store the examples use, and
createGitWorktreeProvider the workspace provider. The guides are
Outside graph types and Graph executor.
Options
recordTo and resume
recordTo appends every event as one JSON line to the file you name, or
under .obversa/records with 'auto'. resume: true reads that record
first: a workflow(), a dag() or a loop() carries on from it in the
round it reached; a plain job appends to it and runs again. A finished
step is reused while the files it declares are still in the workspace. A
graph that runs in many rounds, such as a loop’s body, reuses the steps it
finished in each round. To resume, keep the graph’s name, workspace and
shape the same (for a workflow, its brief, stage list and role seats too);
change any and the run starts again.
The record says what a resumed run repeats.
A fresh run never writes over a record. When the file already holds one,
it moves beside the new one, with the time it was last written in its
name. The run leaves those earlier records, its own record and the full
output of its checks out of every snapshot, review and commit. A step that
takes its own snapshot with workspaceTree passes
ctx.fingerprintExcludePaths as excludePaths to leave the same files out.
A resume also reads back what a proof check kept: the proofs it accepted,
and its send-backs so far. proofSendBacks(ctx) gives the count and the
report the last send-back read. noteProofSendBack(ctx, report) counts one
more; put what it returns in the outcome’s data.proofSendBacks, so the
record keeps it.
carryFrom
carryFrom names the record of an earlier run on the same work. The run
reads three things from it and gives them to every step as ctx.carried:
- The open findings. These are the last finished review’s findings that were never resolved. A finding the judge skipped is not open.
- The accepted proofs. Each proof the earlier run’s proof check accepted, with the tree it was accepted on and the files it covers.
- How it ended. The step that stopped it, its status and its reason.
carryFrom may name the recordTo path. The run reads the earlier record
before it moves aside.
commit
commit commits the worktree’s changes on its branch when the run passes,
before the run reports. The message is the last fenced block marked
commit in the output of the step that commit: { from } names. With
commit: true, the run uses the step the workflow names: a dag() names
one with its own commit: { from }. The run then adds its trailers: Run:,
and Review-rounds: and Reviewed-by: when a panel reviewed the work.
The repository’s own git setup signs the commit.
A hook can refuse the commit, for example outside the hours a repository
allows commits. The run still passes. It leaves the work uncommitted and
says why on outcome.commit and in the record. The run never pushes.
callbacks and onCallback
callbacks is the client the run’s questions go through, in memory (the
default, fresh per run) or stored. onCallback: 'wait' keeps the process
up until an answer arrives; the default 'exit' records the question and
returns, so a schedule can start the same file again until the answer is
there. A record written in one mode resumes in the other.
engine and engines
engines is the map of ready-made engine instances by name, and engine
the one a job or condition uses when it names none. The runtime imports no
adapter, so both are yours to supply. withEnv(job, env) pins environment
variables for a job and every job beneath it.
The rest
Node keys
The fields adag() node takes. A pipeline() step takes the same fields
except retrySafe and the timeout and output bounds.
review() keys
The fields review({ ... }) takes, on a node’s refine. A review needs
rounds or judge; the two cannot be given together.
Stage keys
Workflow keys
Errors
LoopErrorcarries acode:ENGINE,TIMEOUT,ABORTED,VALIDATION,WRITE_BOUNDARY,CONFIG,BUDGET,RATE_LIMIT,QUOTA,BODYorUNKNOWN, and aphase:start,body,until,stopOn,revieworengine.WorkspacePolicyError:INVALID_WORKSPACE_POLICY,NOT_GIT_REPOSITORY,GIT_INSPECTION_FAILED,ABORTED.EngineIdentityUnresolvedError: a recorded auth failure names no provider and the lane can’t supply one.- Re-exported from
@obversa/api:EngineError,EngineIncompleteResultError,GraphValidationError,GraphExecutionError,StorageError,ApprovalSubjectError,JsonValueError. Their codes are on API.
API
Declare a team.workflow, stage, person, briefFromFile,
formatEvent, defineJob (returns the job it’s given, so a file’s default
export keeps the exact Job type), defineAgent, defineAgentFromMarkdown,
defineSkill, fromFile.
Build a graph. dag, pipeline, sequence, parallel, loop,
fnJob, agentJob, commandJob, commandSucceeds, gateJob, prove,
isolated, writeScope, team, jobMeta, copyJobMeta, renderPlan,
assertGraph, withEnv, seatsOf.
Conditions. passed, failed, all, any, not, always, never,
predicate, toCondition, describeConditions, bodyPassed, quorum,
sampled, ratchet, agentCheck, confidenceCondition, minConfidence,
confidenceFromText, lastDecisionLine, lastGateBrief, reviewContext.
Review. review, isReview, reviewPanel, goalCheck, tournament, kickback, revisionRequest, judge, isJudge, stopQuestions, findingQuestions, FINDING_LEVELS, JUDGE_CONFIDENCE,
RECORDED_ENGINE_USAGE, RESUME_STAGE_OUTCOMES, changeUnderReview,
changeTooLarge, workspaceTree, diffTrees, inputLimitCharacters,
CHARACTERS_PER_TOKEN.
Proofs and carried work. acceptedProofs, acceptProofs,
standingProofs, proofSendBacks, noteProofSendBack, readCarry,
commitMessageIn, failingTests, failureLines.
Ask a person. approval, createCallbackGate, createCallbackClient,
createStoredCallbackClient, replayCallbackClient, directRouter,
callbackRequestDigest, createApprovalCallbackGate,
approvalSubjectDigest, resolveApproval.
Run. run, EXIT_PAUSED, exitCodeFor, costReport,
formatCostReport, renderRecord, summarizeRecord,
preflight, preflightEngine, formatPreflight,
fallbackEngine, classifyEngineFailure, LANE_DEAD_FAILURES,
fileAvailabilityStore,
finalResultPart, finalResultText, validateAgentResult.
Evidence. writeProofArtifact, createAcceptedResultRecord,
resolveAcceptedResult, acceptedResultMatches, createProofCache.
Graph layer. compileGraph, resolveGraphPlan, validateGraphDescription,
persistRunDefinition, loadRunDefinition, createGraphExecutor,
readRunPreflight, interruptRunPreflight, dagGraphType, convergence,
teamGraphType, projectTeamRooms, createGitWorktreeProvider, and the
validate* functions for stored records, re-exported from @obversa/api.
Subpaths. @obversa/runtime/testing: MockEngine, MockEnvironment,
mockVerdict, recordedJudge (replays a judge’s recorded answers from a
JSON file, one answer object per round, in place of jev()), defineGraphDefinition,
createGraphEventTrace, and the conformance kits. @obversa/runtime/memory: ground, curate,
consolidate. @obversa/runtime/workflow-support: outcomeFromAgentText,
INVALID_TEAM_DECISION, seatIdentity, assertDistinctSeats,
requireNonEmptyFiles, requireNoFiles, teamAgent, panelReviewers,
objectAt. @obversa/runtime/env/command: commandEnvironment.
@obversa/runtime/storage/local: createLocalRunStorage.
Next steps
- Workflows: the idea behind
workflow()and the stages. - Feature delivery: a complete workflow with model reviews and human approval.
- Running: what
run()records and what a resumed run repeats.