$ recombobulate _
home / tips / track-claude-code-costs-and-duration-in-automated-runs
0

Track Claude Code Costs and Duration in Automated Runs

bagwaa @bagwaa · Mar 26, 2026 · Performance
track-claude-code-costs-and-duration-in-automated-runs

When you run Claude Code with --output-format json, every response includes metadata alongside the result that you can use to monitor your automation costs:

claude -p "Review the latest commit for issues" --output-format json

The JSON envelope always contains:

{
  "result": "The commit looks good overall...",
  "cost_usd": 0.0032,
  "duration_ms": 4812,
  "session_id": "sess_abc123",
  "is_error": false
}

Extract just the cost after every CI run using jq:

output=$(claude -p "Run the security audit" --output-format json)
cost=$(echo "$output" | jq -r '.cost_usd')
echo "Audit complete. Cost: \$$cost"

Fail the build automatically if a single run costs more than expected — a signal that something has gone wrong:

if (( $(echo "$cost > 0.10" | bc -l) )); then
  echo "Warning: unexpectedly high cost — check prompt or turn limits"
  exit 1
fi

Log costs over time to a CSV for cumulative tracking:

echo "$(date),$(echo "$output" | jq -r '.cost_usd'),$(echo "$output" | jq -r '.duration_ms')" \
  >> ci_costs.log

A single run that suddenly costs 10x the usual amount is a strong signal the prompt hit an edge case or the model got stuck in a loop. Tracking this per-run lets you catch it before it becomes a real bill.

Pair with --max-budget-usd as a hard ceiling so costs never exceed your limit even if you forget to check the log.

Per-run cost visibility is the first step to keeping Claude Code automation bills predictable.

~/recombobulate $ tip --comments --count=0

Log in to leave a comment.

~/recombobulate $ tip --related --limit=3
0
Filter Test Output with a PreToolUse Hook to Cut Token Costs

A PreToolUse hook can intercept test runner commands and filter output to show only failures, cutting thousands of tokens from Claude's context.

bagwaa @bagwaa · 3 hours ago
0
Move Specialised CLAUDE.md Instructions into Skills to Shrink Context

CLAUDE.md loads into every message. Move workflow-specific instructions into skills that load on demand to reduce token costs across your session.

bagwaa @bagwaa · 3 hours ago
0
Use prompt.id to Trace All Activity from a Single User Prompt

Every event emitted while processing a single prompt shares a prompt.id UUID, letting you trace the complete chain of API calls and tool executions.

bagwaa @bagwaa · 3 hours ago