Docs/Advanced/Queries & Replay

Queries & Replay

Verify execution integrity, query the semantic behavior graph, replay session timelines, and run counterfactual experiments.

import { Invariance } from '@invariance/sdk';
Prerequisites: Initialization, Tracing & Emit

Overview

The query layer provides verification, graph queries, replay, and counterfactual analysis.

`verify()` validates hash chain integrity and signatures. `queryGraph()` interrogates the semantic behavior graph. `replayTimeline()` returns a chronological timeline of trace events. `counterfactual()` branches from a node with modified inputs for "what if" analysis.

Quick Example

Verify, query, and replaytypescript
const proof = await inv.verify('execution-id');
console.log(proof.valid);

const receipts = await inv.query({ sessionId: 'session-123', action: 'swap' });

const timeline = await inv.replayTimeline('session-123');
for (const entry of timeline) {
  console.log(`${entry.actionType} at ${entry.timestamp} (${entry.durationMs}ms)`);
}

const cf = await inv.counterfactual({
  branchFromNodeId: 'node-456',
  modifiedInput: { query: 'different search' },
  tag: 'experiment-1',
});

Type Definitions

VerificationProof
interface VerificationProof {
  valid: boolean;
  executionId: string;
  chain: Array<{ nodeId: string; hash: string; actionType: string; anomalyScore: number }>;
  signedBy: string;
  anchored: boolean;
  tamperedNodes?: string[];
}
Cryptographic proof of execution integrity.
ReceiptQuery
interface ReceiptQuery {
  sessionId?: string;
  agent?: string;
  action?: string;
  fromTimestamp?: number;
  toTimestamp?: number;
  limit?: number;
  offset?: number;
}
Filters for querying receipts.
EvalSuite
interface EvalSuite {
  add(name: string, fn: (query: TraceQuery) => void): this;
  addJudge(name: string, config: {
    prompt: string;
    provider: (prompt: string) => Promise<string>;
  }): this;
  run(receipts: readonly Receipt[]): Promise<EvalResult[]>;
}
A composable evaluation suite for testing agent behavior. Supports programmatic assertions via add() and LLM-based judges via addJudge().
EvalResult
interface EvalResult {
  name: string;
  passed: boolean;
  error?: string;
  durationMs: number;
  type: 'assertion' | 'judge';
}
Result of a single eval check or judge evaluation.
TraceQuery
interface TraceQuery {
  ofType(actionType: string): TraceQuery;
  byAgent(agent: string): TraceQuery;
  withError(): TraceQuery;
  where(predicate: (r: Receipt) => boolean): TraceQuery;
  inTimeRange(from: number, to: number): TraceQuery;
  all(): Receipt[];
  count(): number;
  first(): Receipt | undefined;
}
Chainable query builder for filtering and analyzing receipts. Supports fluent method chaining with terminal methods all(), count(), and first().

API Reference

verify
Verify cryptographic integrity of an execution.
async verify(executionId: string): Promise<VerificationProof>
Parameters
executionIdstringExecution or session ID to verify
ReturnsPromise<VerificationProof>
query
Query receipts from the API with filters.
async query(filters: ReceiptQuery): Promise<Receipt[]>
Parameters
filtersReceiptQueryFilter by session, agent, action, time range
ReturnsPromise<Receipt[]>
queryGraph
Query the semantic behavior graph.
async queryGraph(query: string): Promise<unknown>
Parameters
querystringGraph query string
ReturnsPromise<unknown>
replayTimeline
Get the replay timeline for a session.
async replayTimeline(sessionId: string): Promise<ReplayTimelineEntry[]>
Parameters
sessionIdstringSession to replay
ReturnsPromise<ReplayTimelineEntry[]>
nodeSnapshot
Get the full replay snapshot for a trace node.
async nodeSnapshot(nodeId: string): Promise<ReplaySnapshot | null>
Parameters
nodeIdstringTrace node ID
ReturnsPromise<ReplaySnapshot | null>
counterfactual
Branch from a node with modified inputs for "what if" analysis.
async counterfactual(request: CounterfactualRequest): Promise<CounterfactualResult>
Parameters
requestCounterfactualRequestBranch point and modified input
ReturnsPromise<CounterfactualResult>
traces
Create a TraceQuery over a session's trace nodes.
async traces(sessionId: string): Promise<TraceQuery>
Parameters
sessionIdstringSession to query
ReturnsPromise<TraceQuery>
ask
Ask a natural language question about agent data.
async ask(question: string, scope?: NLQueryScope): Promise<NLQueryResult>
Parameters
questionstringNatural language question
ReturnsPromise<NLQueryResult>
queryTraces
Query traces using natural language against the trace query backend.
async queryTraces(query: string, opts?: { session_id?: string; agent_id?: string; limit?: number; llm?: boolean }): Promise<TraceQueryResult>
Parameters
querystringNatural language trace query
opts{ session_id?: string; agent_id?: string; limit?: number; llm?: boolean }Optional filters and execution flags
ReturnsPromise<TraceQueryResult>
queryTracesStructured
Query traces with a structured AST payload.
async queryTracesStructured(ast: Record<string, unknown>): Promise<TraceQueryResult>
Parameters
astRecord<string, unknown>Structured trace query AST
ReturnsPromise<TraceQueryResult>
getStats
Fetch aggregate stats for a session or agent.
async getStats(opts?: { session_id?: string; agent_id?: string }): Promise<StatsResult>
Parameters
opts{ session_id?: string; agent_id?: string }Optional session or agent selector
ReturnsPromise<StatsResult>
writeNote
Write a durable agent note keyed for later retrieval.
async writeNote(key: string, content: unknown, opts?: { session_id?: string; node_id?: string; ttl_hours?: number }): Promise<AgentNote>
Parameters
keystringNote key
contentunknownJSON-serializable note content
opts{ session_id?: string; node_id?: string; ttl_hours?: number }Optional scope and TTL
ReturnsPromise<AgentNote>
readNote
Read an agent note by key.
async readNote(key: string): Promise<AgentNote | null>
Parameters
keystringNote key
ReturnsPromise<AgentNote | null>
getToolSchemas
Fetch tool schemas exposed by the trace query backend.
async getToolSchemas(): Promise<ToolSchema[]>
ReturnsPromise<ToolSchema[]>
liveStatus
Create a LiveStatusClient for the backend SSE stream.
liveStatus(opts: Omit<LiveStatusClientConfig, "apiUrl" | "apiKey">): LiveStatusClient
Parameters
optsOmit<LiveStatusClientConfig, "apiUrl" | "apiKey">Live status client options
ReturnsLiveStatusClient
eval
Create an EvalSuite for testing agent behavior with programmatic assertions and LLM judges. Chain .add() for deterministic checks and .addJudge() for LLM-based evaluation.
eval(): EvalSuite
ReturnsEvalSuite

Use Cases

  • Verify agent execution integrity before acting on results
  • Query receipts for audit or compliance reporting
  • Replay failed agent sessions to debug issues
  • Run counterfactual experiments to test alternative strategies
  • Ask natural language questions about agent behavior
On this page
OverviewQuick ExampleType DefinitionsAPI ReferenceUse CasesRelated Modules