@noetaris/harness-recorder
v0.2.1
Published
Step recorder and trace stores for @noetaris/harness playback
Readme
@noetaris/harness-recorder
Records each step of an agent's runs, and plays a finished session back step by step — without running any step again.
createRecorder— anObserverthat writes every step of every run to a trace store, in the backgroundInMemoryTraceStore,LocalFileTraceStore— where the records goloadPlayback— rebuilds a recorded session: its runs, its steps, and the state before and after each step
Installation
pnpm add @noetaris/harness-recorderPeer dependency:
pnpm add @noetaris/harness # 0.14.0 or laterPlayback also needs a session store that implements loadHistory (see Playback).
The quick start uses the in-memory one:
pnpm add @noetaris/harness-storeQuick start
import { createHarness, createAgent, field } from '@noetaris/harness'
import { InMemorySessionStore } from '@noetaris/harness-store'
import { createRecorder, InMemoryTraceStore, loadPlayback } from '@noetaris/harness-recorder'
const schema = {
notes: field<string[]>({ default: () => [], reduce: (a, b) => [...a, ...b] }),
done: field<boolean>(),
}
const sessions = new InMemorySessionStore()
const h = createHarness()(schema)
.store({ session: sessions })
.loop((l) => {
l.start()
.step('collect', { run: async () => ({ notes: ['a'] }) })
.step('more', { run: async () => ({ notes: ['b'] }) })
.step('finish', { run: async () => ({ done: true }), route: () => 'ok' })
.on('ok').end()
})
// Record every run of this agent.
const traces = new InMemoryTraceStore()
const recorder = createRecorder(traces, { level: 'record', version: 'abc123' })
const agent = createAgent('notes', h, {}, { observer: recorder })
await agent.run({}, { sessionId: 's1' })
await recorder.flush() // writes happen in the background; wait for them before reading
// Play the session back.
const playback = await loadPlayback({
traceStore: traces, sessionStore: sessions, agentId: 'notes', sessionId: 's1', schema, version: 'abc123',
})
for (const step of playback.steps) {
const { after } = playback.stateAt(step.index)
console.log(step.step, step.update, after.known ? after.values : after.reason)
}
// collect { notes: [ 'a' ] } { notes: [ 'a' ] }
// more { notes: [ 'b' ] } { notes: [ 'a', 'b' ] }
// finish { done: true } { notes: [ 'a', 'b' ], done: true }createAgent's observer option records every run of the agent: agent.run(), handle.resume()
and agent.resume(). You can also pass the recorder per run as observer in agent.run()'s
resources; then only that run chain is recorded.
Recording
Levels
createRecorder(store, { level: 'record' })
createRecorder(store, { level: (ctx) => (ctx.sessionId.startsWith('debug-') ? 'record' : 'trace') })| Level | Stored per step | Playback |
|---|---|---|
| off | nothing | — |
| trace (default) | step name, branch path, outcome, duration, signal, next, error, interrupt id | the path the run took; no per-step state |
| record | trace + the step's update, the interrupt prompt, and debug setState values | the path and the state before and after every step |
trace costs almost nothing. record adds a few microseconds per step, whatever the size of the
state, because it stores each step's update (what the step returned), not the state. A 200-step run
with ~1 KB updates writes about 220 KB.
The level function is called once when each top-level run starts (a resumed run is a new run).
If it throws or returns something that is not a level, the run is recorded at trace and
onError is told (kind: 'level').
What is recorded
Each session is one stream of records, in order:
| Record | When |
|---|---|
| run-start | a top-level run starts: its runId, level, version, and the run it resumes or continues |
| step | a step settles (fired once per step, on every path, by Observer.onStepSettled) — fork branch steps carry branchPath |
| patch | a debug session's setState (see the core README, "Debugging a run") changed state before a step |
| run-end | the run ends: its signal, and the error if it ended with one |
| gap | records were lost here (see below) |
Updates, prompts and patch values are stored as JSON, copied when the step settles. A Date
becomes a string, undefined keys disappear, a Map becomes {}. A value JSON can't hold (a
BigInt, a cycle) is left out and the record says why (updateError, promptError,
patchError).
Buffering and faults
Recording never blocks, slows or fails a run. Hooks only copy what they need and queue it; the queue is written in the background, one append at a time per session.
- At most
maxBufferedrecords are held at once, over all sessions, including the ones being written. Default: themaxBufferedoption, else theHARNESS_RECORDER_MAX_BUFFEREDenvironment variable, elseDEFAULT_MAX_BUFFERED(10 000). - A record that doesn't fit is dropped. A write the store fails is not retried. Either way a
gaprecord marks the hole, with how many records were lost. - Store failures go to
onError(error, { kind: 'store', sessionId }); the default logs withconsole.warn. recorder.flush()resolves once every record buffered when you call it is written or failed. It never rejects, but it waits for a write in progress — if your store can hang, race it with a timeout.
Version
Pass version (a git SHA, a release number) to write it on every run-start. Playback replays
updates through your current reducers; when the code that recorded a run differs from the code
playing it back, loadPlayback({ version }) warns (version-mismatch, or version-unknown for a
run recorded without one). Without a version, nothing is checked.
Trace stores
A trace store keeps records per (agentId, sessionId). It is separate from the session store:
the session store is for resuming, the trace store is for playback, with its own retention.
| Store | Use |
|---|---|
| new InMemoryTraceStore() | tests and local use; unbounded |
| new LocalFileTraceStore({ dir }) | one JSONL file per session at {dir}/{agentId}/{sessionId}.jsonl; directories are created on the first write; ids are encoded the same way as LocalFileSessionStore, so any id maps to its own file inside dir. A torn last line (a crash mid-write) is skipped on load |
Your own store implements two methods:
interface TraceStore {
/** Append in order. The recorder never has two appends in flight for one session. */
append(agentId: string, sessionId: string, records: readonly TraceRecord[]): Promise<void>
/** Every record of the session in append order; [] for an unknown session. */
load(agentId: string, sessionId: string): Promise<TraceRecord[]>
}Playback
loadPlayback
const playback = await loadPlayback({
traceStore, // where the recorder wrote
sessionStore, // the agent's session store; must implement loadHistory
agentId,
sessionId,
schema, // optional: the schema given to createHarness, for its reducers
version, // optional: compared with each run's recorded version
})Playback needs every run's starting state, which only the session store has (loadHistory):
| Session store | Playback |
|---|---|
| InMemorySessionStore, LocalFileSessionStore (@noetaris/harness-store) | yes |
| @noetaris/harness-store-postgres | yes |
| @noetaris/harness-store-redis | no — it keeps only the latest run |
With a store that has no loadHistory, loadPlayback throws PlaybackUnsupportedStoreError
before reading anything.
Playing back from another process
The quick start records and plays back in one process. In practice playback usually runs
somewhere else: a support tool, a CLI, another machine. loadPlayback does not need the agent,
the recorder or the objects they were given — only stores that read the same storage. Create
new store instances that point at it:
process A (runs the agent) process B (plays back)
────────────────────────── ──────────────────────
createRecorder(new LocalFileTraceStore({ dir })) new LocalFileTraceStore({ dir }) same dir
h.store({ session: new PostgresSessionStore(…) }) new PostgresSessionStore(…) same database
│ │
└──────────────▶ files / database ◀────────────┘// process B
import { LocalFileTraceStore, loadPlayback } from '@noetaris/harness-recorder'
import { PostgresSessionStore } from '@noetaris/harness-store-postgres'
import { schema } from './my-agent/harness.js' // the agent's own schema, for its reducers
const playback = await loadPlayback({
traceStore: new LocalFileTraceStore({ dir: '/shared/traces' }),
sessionStore: new PostgresSessionStore({ pool }),
agentId: 'notes',
sessionId,
schema,
version: process.env.GIT_SHA,
})Where each store can be read from:
| Store | Same process | Another process, same machine | Another machine |
|---|---|---|---|
| InMemoryTraceStore, InMemorySessionStore | yes | no | no |
| LocalFileTraceStore, LocalFileSessionStore | yes | yes (same dir) | only through a shared volume |
| @noetaris/harness-store-postgres (session store) | yes | yes | yes |
| @noetaris/harness-store-redis (session store) | no playback (no loadHistory) | — | — |
| your own TraceStore | as its storage allows | | |
There is no database-backed trace store yet. To play back from another machine, share the trace
directory or implement TraceStore (two methods) over your own storage.
- The schema comes from the agent's code. Process B imports the same
schemaobject the harness was created with. Passversionon both sides to be warned when the code differs. - Records still buffered in process A are not visible. Process A writes in the background;
B sees what has been written so far. A run that is still going, or whose process died, has no
endand may have fewer steps than it ran.
Runs and steps
| Field | What it is |
|---|---|
| playback.runs | every run of the session, in order: its runId, stored start and final state and the phase of its last stored record (stored.phase), level, version, how it ended, the range of its steps, interrupt answers |
| playback.steps | every step attempt of the session, flat, in order: name, branchPath, outcome, signal, next, update, error, interrupt |
| playback.stateAt(i) | { scope, before, after }: the state step i saw and left |
| playback.warnings | what didn't line up (see below) |
stateAt rebuilds state from the run's stored start state plus each recorded update, applying
reducers the same way the loop does. Framework keys ($error, $interrupt,
$interruptResponses) are left out.
- Forks. A step inside a fork branch is shown in its branch's own state:
scopeis its branch path ([]at the top level). The fork step'safteris the state after the join; for a fork that paused or failed it equals itsbefore. The join is rebuilt by the loop's rule: a key one branch wrote takes that branch's value; a key several branches wrote gets each branch's recorded updates folded in with its reducer, branch after branch in declaration order. When a branch returned an update for the key that is not plain JSON data, the loop folds that branch's whole value of the key instead; the recorder notes those keys on the branch step's record (nonJsonKeys) so playback does the same. In a nested fork, a branch that holds an inner fork is folded by its whole value too when one of the inner branches was. This rule needs the@noetaris/harnessversion that savesBranchCursor.writesin a paused fork's cursor, for recording and for playback. With an older core, or for a session an older core recorded, playback reports a falsefinal-state-mismatchfor a fork whose branches wrote a reducer key that was not empty before the fork. - Interrupts. A step that interrupts appears twice: the attempt that paused (with
answeronce the session was resumed) and the attempt that ran again (withattemptOf= the index of the first). - Stops. A step cut by
handle.stop()or the caller's signal hasoutcome: 'stopped', and the session pauses on it. When the next run executes it again, that attempt hasattemptOf= the index of the stopped one. - Debug edits.
setStatechanges recorded atrecordlevel are listed on the next step (patchesBefore) and applied before it.
Crashed and continued runs
With checkpoint: 'step' (see the core README, "Checkpoints"), the session is saved after every
finished step, so one run can have several stored records. run.stored takes the start state from
the run's first record and the final state, step and phase from its last.
stored.phase === 'running': the last record is a checkpoint. The run did not settle in the store — its process died, or it lost the session to another instance. Its stored final state is the last checkpoint's, and the run may have gone further.- No
final-state-mismatchis reported for such a run: its stored final state is not where the run ended. - The next run starts from that checkpoint. The step it runs again is a new step attempt; it is
not linked by
attemptOf, which is for interrupted and stopped steps only. - Records still buffered when the process died are lost, and nothing warns about it: the run has
no
endand may show fewer steps than it ran.
When state is unknown
A state view is { known: true, values } or { known: false, reason }. Once a state is unknown,
it stays unknown until the run ends; the next run starts again from its stored start state.
| reason | Cause |
|---|---|
| trace-level | the run was recorded at trace (no updates) |
| no-initial-state | the session store has no row for this run |
| update-error | the step's update could not be stored as JSON |
| patch-error | a debug patch has no values, or records were lost between it and its step |
| gap | records were lost before this step |
| no-branch-state | a fork resumed from a pause, but the run's saved cursor (with the branch states) is missing |
| missing-fork-record | branch steps were recorded but their fork step was not |
| missing-reducer | branches wrote the same key and the schema has no reducer for it |
| reducer-error | a reducer threw while replaying |
playback.warnings lists, with the run and step it concerns: gap, final-state-mismatch (the
rebuilt end state differs from the stored one — often a wrong schema), version-mismatch,
version-unknown, missing-reducer, reducer-error, unknown-record, missing-run-start and
unmatched-patch.
Schema
Pass the same schema object you gave createHarness, so keys with a reduce function are merged
as they were in the run. Without it every update overwrites. A wrong schema shows up as a
final-state-mismatch warning at the end of the run.
API
| Export | Description |
|---|---|
| createRecorder(store, options?) | Returns a Recorder: an Observer with flush(). Options: level, version, maxBuffered, onError. Throws RangeError for an unknown level or a maxBuffered that is not an integer > 0 |
| Recorder, RecorderOptions, RecorderErrorInfo, Level | Recorder types |
| DEFAULT_MAX_BUFFERED | 10 000 |
| InMemoryTraceStore, LocalFileTraceStore, LocalFileTraceStoreOptions | Trace stores |
| TraceStore | Trace store interface |
| TraceRecord, RunStartRecord, StepRecord, PatchRecord, RunEndRecord, GapRecord, RecordedError | Record shapes |
| loadPlayback(options) | Loads a session for playback. Returns a Playback |
| Playback, PlaybackRun, PlaybackStep, StateView, UnknownReason, PlaybackWarning, LoadPlaybackOptions | Playback types |
| PlaybackUnsupportedStoreError | The session store has no loadHistory |
Limitations
LocalFileTraceStorehas no locking: use one process per directory.flush()waits for a write in progress; a store call that never settles keeps it waiting.- Sessions in the Redis session store cannot be played back (no
loadHistory). - Records still buffered when the process exits are lost; call
flush()before a graceful shutdown. After a crash this is not reported: a run continued from a checkpoint may show fewer steps than it ran.
License
MIT
