session.json in the audit logs directory.
MetricsTracker Class
TheMetricsTracker class manages all metrics for a session:
src/audit/metrics-tracker.ts:85
Key Methods
initialize(workflowId?: string)- Initialize or load existing session.jsonstartAgent(agentName, attemptNumber)- Start timing an agent executionendAgent(agentName, result)- End timing and update metricsupdateSessionStatus(status)- Update session completion statusaddResumeAttempt(workflowId, terminatedWorkflows, checkpointHash)- Track workflow resumegetMetrics()- Get current metrics snapshotreload()- Reload metrics from disk
SessionData Structure
The complete session data structure persisted tosession.json:
src/audit/metrics-tracker.ts:58
Session Metadata
id- Unique session identifier (format:{hostname}_{timestamp})webUrl- Target web application URLrepoPath- Path to target repository (optional)status- Current session statuscreatedAt- ISO 8601 timestamp when session was createdcompletedAt- ISO 8601 timestamp when session completed (if finished)originalWorkflowId- First workflow ID that created this workspaceresumeAttempts- Array of resume attempt records
Session Status Values
in-progress- Session is currently executingcompleted- Session completed successfullyfailed- Session failed permanently
AgentMetrics Interface
Metrics returned by the Claude SDK after agent execution:src/types/metrics.ts:12
Field Descriptions
durationMs- Execution time in millisecondsinputTokens- Total input tokens consumed (null if unavailable)outputTokens- Total output tokens generated (null if unavailable)costUsd- Total cost in USD (null if unavailable)numTurns- Number of agent turns executed (null if unavailable)model- Claude model used (e.g., “claude-3-5-sonnet-20241022”)
AgentAuditMetrics Structure
Per-agent metrics tracked insession.json:
src/audit/metrics-tracker.ts:35
Agent Status Values
in-progress- Agent is currently executingsuccess- Agent completed successfullyfailed- Agent failed after all retry attempts
Metrics Fields
status- Current agent execution statusattempts- Array of all execution attempts (including failures)final_duration_ms- Duration of successful attempt (0 if failed)total_cost_usd- Sum of costs across all attemptsmodel- Claude model used for successful attemptcheckpoint- Git checkpoint hash for successful attempt
AttemptData Structure
Detailed data for each execution attempt:src/audit/metrics-tracker.ts:25
Field Descriptions
attempt_number- Attempt number (1, 2, 3)duration_ms- Execution time for this attemptcost_usd- Cost incurred for this attemptsuccess- Whether this attempt succeededtimestamp- ISO 8601 timestamp when attempt startedmodel- Claude model used (optional)error- Error message if attempt failed (optional)
PhaseMetrics Structure
Aggregated metrics per pipeline phase:src/audit/metrics-tracker.ts:44
Field Descriptions
duration_ms- Total duration for all agents in this phaseduration_percentage- Percentage of total session durationcost_usd- Total cost for all agents in this phaseagent_count- Number of agents in this phase
Phase Names
src/session-manager.ts:111
Resume Tracking
Resume attempts are tracked for crash recovery and debugging:src/audit/metrics-tracker.ts:51
Field Descriptions
workflowId- New workflow ID for this resume attempttimestamp- ISO 8601 timestamp when resume was triggeredterminatedPrevious- Comma-separated list of terminated workflow IDsresumedFromCheckpoint- Git checkpoint hash that was restored
AgentEndResult
Data passed toMetricsTracker.endAgent() when an agent completes:
src/types/audit.ts:26
Metrics Calculation
Total Duration and Cost
Only successful agents count toward totals:src/audit/metrics-tracker.ts:315
Phase Metrics
Agents are grouped by phase usingAGENT_PHASE_MAP:
src/audit/metrics-tracker.ts:335
Duration Percentage
Calculated as percentage of total session duration:src/audit/metrics-tracker.ts:361
Cost Tracking
Per-Attempt Cost
Each attempt tracks its own cost, including failed attempts:Total Agent Cost
Sum of all attempts (successes + failures):src/audit/metrics-tracker.ts:204
Session Total Cost
Sum of successful agents only:Total cost includes failed attempts. If an agent fails twice and succeeds on the third attempt, all three attempts’ costs are included in
total_cost_usd.Turn Counting
ThenumTurns field tracks how many agent-environment interaction turns occurred:
Atomic Writes
All metrics updates use atomic writes to prevent corruption:src/audit/metrics-tracker.ts:382
Atomic writes prevent partial writes if the process crashes mid-write.
Session.json Example
Metrics Aggregation Workflow
- Agent Start -
MetricsTracker.startAgent()records start time - Agent Execution - Claude SDK runs agent and returns
AgentMetrics - Agent End -
MetricsTracker.endAgent()receivesAgentEndResult - Attempt Recording - Attempt data appended to agent’s attempt history
- Status Update - Agent status updated to ‘success’ or ‘failed’
- Cost Calculation - Total cost recalculated across all attempts
- Phase Aggregation - Phase metrics recalculated from successful agents
- Session Totals - Session-level totals recalculated
- Atomic Write - All metrics saved to session.json atomically
Metrics Location
Default Path:./audit-logs/{hostname}_{sessionId}/session.json
Override: Set OUTPUT=<path> environment variable
Related Documentation
- Agent Registry - Agent definitions and execution flow
- Error Handling - Error tracking in metrics
- Key Files - Metrics file locations
