Docs/Advanced/Tracing & Emit

Tracing & Emit

Instrument agent behavior with trace events and behavioral primitives. DEV mode (full fidelity) and PROD mode (sampled, signed) for observability without receipt overhead.

import { Invariance } from '@invariance/sdk';
Prerequisites: Initialization

Overview

`trace()` wraps a function with timing, hashing, anomaly scoring, and optional replay snapshots. Unlike `wrap()`, it does NOT create receipts — use it for debugging and monitoring.

`emit()` records behavioral primitives to the semantic behavior graph: DecisionPoint, GoalDrift, SubAgentSpawn, and ToolInvocation. These power anomaly detection, drift analysis, and the replay debugger. Emit is fire-and-forget.

The SDK supports DEV (full fidelity, no crypto overhead) and PROD (sampled, anomaly-scored, signed) modes.

Important Notes

trace() vs wrap()
trace() is for observability (no receipts). Use wrap() for cryptographic audit trails.
DEV mode for development
Use mode: "DEV" during development for full tracing. Switch to "PROD" for production.

Quick Example

Trace actions and emit behavioral eventstypescript
const inv = Invariance.init({
  apiKey: 'dev_...', mode: 'DEV', devOutput: 'console',
  onAnomaly: (event) => console.warn('Anomaly:', event.anomalyScore),
});

const { result, event } = await inv.trace({
  agentId: 'research-agent',
  action: { type: 'ToolInvocation', tool: 'web_search', input: { query: 'AI safety' } },
  fn: () => searchWeb('AI safety'),
});

console.log(event.durationMs);
console.log(event.anomalyScore);

inv.emit('DecisionPoint', {
  nodeId: event.nodeId,
  candidates: ['search', 'summarize', 'report'],
  chosen: 'search',
  depth: 0,
});

Type Definitions

TraceEvent
interface TraceEvent {
  schemaVersion: string;
  nodeId: string;
  sessionId: string;
  agentId: string;
  actionType: BehavioralPrimitive;
  input: unknown;
  output?: unknown;
  timestamp: number;
  durationMs: number;
  hash: string;
  previousHash: string;
  anomalyScore: number;
}
A trace event with timing, hashing, and anomaly scoring.
BehavioralPrimitive
type BehavioralPrimitive =
  | 'DecisionPoint' | 'ToolInvocation'
  | 'SubAgentSpawn' | 'GoalDrift'
  | 'ConstraintCheck' | 'PlanRevision'
  | 'A2ASend' | 'A2AReceive';
Types of behavioral events for the semantic graph.

API Reference

trace
Trace an agent action for observability. Captures timing, hash, anomaly scoring. Does NOT create receipts.
async trace<T>(params: { agentId: string; action: TraceAction; fn: () => T | Promise<T>; sessionId?: string; parentNodeId?: string; metadata?: object }): Promise<{ result: T; event: TraceEvent }>
Parameters
agentIdstringAgent performing the action
actionTraceActionAction type, tool name, and input
fn() => T | Promise<T>Function to execute and trace
ReturnsPromise<{ result: T; event: TraceEvent }>
emit
Emit a behavioral primitive event. Fire-and-forget — never blocks agent execution.
emit(type: BehavioralPrimitive, data: PrimitivePayload): void
Parameters
typeBehavioralPrimitiveEvent type
dataPrimitivePayloadEvent-specific payload
Returnsvoid

Configuration

OptionTypeDefaultDescription
mode'DEV' | 'PROD''PROD'DEV captures everything; PROD samples and signs
sampleRatenumber0.01Fraction of events to trace in PROD mode
anomalyThresholdnumber0.7Minimum score to trigger onAnomaly callback
devOutput'ui' | 'console' | 'both''console'Where to output trace data in DEV mode
captureReplaySnapshotsbooleanfalseWhether to capture full input/output snapshots for replay debugging
replayContext{ type: 'full' } | { type: 'last' } | { type: 'window', size: number }{ type: 'last' }Controls how much context is included in replay snapshots. "full" captures entire history, "last" captures only the most recent event, "window" captures the last N events.

Use Cases

  • Profile agent execution time and identify bottlenecks
  • Detect anomalous agent behavior with automatic scoring
  • Track decision-making patterns and identify goal drift
  • Build replay capability for debugging agent failures
  • Monitor sub-agent spawning depth and patterns
On this page
OverviewImportant NotesQuick ExampleType DefinitionsAPI ReferenceConfigurationUse CasesRelated Modules