Repository navigation
Description
Problem
When a sequant run completes, users see the total token count but have no visibility into where those tokens went. Did the QA phase use 3x more than expected? Did one exec agent burn through most of the budget while others finished quickly? Was the spec exploration efficient or did it wander?
This lack of per-subagent visibility makes it impossible to:
- Diagnose expensive runs — "Why did this run cost $4?" requires reading full transcripts
- Tune configuration — Should I use
effort: low? IsmaxTurns: 15too generous or too tight? No data to inform the decision - Compare modes — Is parallel actually cheaper than sequential for this codebase? No per-agent breakdown to compare
Claude Code provides SubagentStart and SubagentStop lifecycle hooks that fire for every subagent spawn/completion. SubagentStop includes agent_transcript_path — the path to the subagent's full transcript, which contains token usage data. This is the hook point for per-agent cost telemetry.
Current Behavior
- Sequant logs phase-level events via
LogWriter(start/end per phase, pass/fail) - No per-subagent data is captured
entirelogs subagent spawn/complete events but without token counts- Users must manually inspect transcripts to understand cost distribution
Desired Behavior
Sequant automatically logs per-subagent timing and token data via lifecycle hooks. This data flows into the existing sequant_logs output so /reflect and manual analysis can use it. Users can see a cost breakdown per phase and per agent type after each run.
Acceptance Criteria
1. SubagentStart hook (P0)
- AC-1:
SubagentStarthook configured in.claude/settings.local.json(or project settings) that logs: timestamp,agent_id,agent_type, issue number (fromSEQUANT_ISSUEenv var) - AC-2: Hook implementation is a shell script at
scripts/hooks/subagent-start.sh - AC-3: Log output goes to
.sequant/logs/agents.jsonl(one JSON line per event)
2. SubagentStop hook (P0)
- AC-4:
SubagentStophook logs: timestamp,agent_id,agent_type, duration (computed from start event),agent_transcript_path - AC-5: Hook extracts token count from the subagent transcript file (parse
agent_transcript_pathfor usage data) - AC-6: If transcript parsing fails (format change, file missing), log the event without token data — do not fail the hook
- AC-7: Hook implementation at
scripts/hooks/subagent-stop.sh
3. Log format (P0)
- AC-8: Each log line is valid JSON with schema:
{
"event": "subagent_start" | "subagent_stop",
"timestamp": "ISO-8601",
"agent_id": "string",
"agent_type": "string",
"issue": "number | null",
"phase": "string | null",
"duration_ms": "number (stop only)",
"tokens": "number | null (stop only)",
"max_turns_hit": "boolean (stop only)"
}- AC-9:
phasefield populated fromSEQUANT_PHASEenv var (spec/exec/qa/test/loop) - AC-10:
max_turns_hitderived from transcript content (detects turn-cap termination)
4. Integration with sequant_logs (P1)
- AC-11:
sequant_logsoutput includes agent summary section: total agents spawned, total agent tokens, breakdown by phase - AC-12: Agent data is read from
.sequant/logs/agents.jsonlduring log aggregation - AC-13: If
agents.jsonldoesn't exist (hooks not configured), the agent summary section is omitted gracefully
5. Cost breakdown report (P1)
- AC-14: After
sequant runcompletes, print a per-phase agent summary:
Agent usage:
spec: 2 agents, ~12k tokens, 8.2s avg
exec: 3 agents, ~85k tokens, 45.1s avg
qa: 3 agents, ~9k tokens, 5.3s avg
total: 8 agents, ~106k tokens
- AC-15: Summary only prints when agent log data is available
- AC-16: Token counts are approximate (parsed from transcripts) — label as "~" to set expectations
6. Hook configuration (P2)
- AC-17: Hooks are auto-configured by
sequant init(added to project settings) - AC-18: Hooks can be disabled via
.sequant/settings.json→hooks.agentTracking: false - AC-19: Documentation in
subagent-types.mdexplains the hook setup and log format
Design Notes
Hook Configuration
{
"hooks": {
"SubagentStart": [
{
"hooks": [
{
"type": "command",
"command": "scripts/hooks/subagent-start.sh"
}
]
}
],
"SubagentStop": [
{
"hooks": [
{
"type": "command",
"command": "scripts/hooks/subagent-stop.sh"
}
]
}
]
}
}SubagentStop Hook Data
The SubagentStop event provides via stdin JSON:
agent_id— unique subagent identifier (same as SubagentStart)agent_type— agent name for matcher filteringagent_transcript_path— path to the subagent's transcript filelast_assistant_message— final response text
The transcript file contains the full conversation including token usage metadata. The hook script parses this for the tokens field.
Token Extraction Strategy
Claude Code transcript files are JSON. Token usage is embedded in the conversation metadata. The hook script uses jq to extract:
#!/bin/bash
# scripts/hooks/subagent-stop.sh
INPUT=$(cat)
TRANSCRIPT_PATH=$(echo "$INPUT" | jq -r '.agent_transcript_path // empty')
AGENT_ID=$(echo "$INPUT" | jq -r '.agent_id')
AGENT_TYPE=$(echo "$INPUT" | jq -r '.agent_type')
TOKENS=""
if [ -n "$TRANSCRIPT_PATH" ] && [ -f "$TRANSCRIPT_PATH" ]; then
TOKENS=$(jq '[.[] | .usage.input_tokens + .usage.output_tokens] | add // 0' "$TRANSCRIPT_PATH" 2>/dev/null || echo "")
fi
# Read start timestamp from temp file (written by subagent-start.sh)
START_FILE="/tmp/sequant-agent-${AGENT_ID}.start"
DURATION_MS=""
if [ -f "$START_FILE" ]; then
START_TS=$(cat "$START_FILE")
NOW_TS=$(date +%s%3N)
DURATION_MS=$((NOW_TS - START_TS))
rm -f "$START_FILE"
fi
echo "{\"event\":\"subagent_stop\",\"timestamp\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",\"agent_id\":\"${AGENT_ID}\",\"agent_type\":\"${AGENT_TYPE}\",\"issue\":${SEQUANT_ISSUE:-null},\"phase\":${SEQUANT_PHASE:+\"$SEQUANT_PHASE\"}${SEQUANT_PHASE:-null},\"duration_ms\":${DURATION_MS:-null},\"tokens\":${TOKENS:-null},\"max_turns_hit\":false}" >> .sequant/logs/agents.jsonlCorrelation Between Start and Stop
agent_id is the correlation key. The start hook writes a temp file with the start timestamp; the stop hook reads it to compute duration. Temp files are in /tmp/sequant-agent-<id>.start and cleaned up after use.
Graceful Degradation
- If
jqis not installed: hooks log events without token data (degrade to timing-only) - If transcript file doesn't exist: log event with
tokens: null - If hooks are not configured: no agent log file created;
sequant_logsskips agent summary - If
/tmpstart file is missing (crash, restart):duration_ms: null
Out of Scope
- Real-time token streaming during agent execution — hooks fire at start/stop only
- Cost in dollars — token-to-dollar conversion depends on model and plan; just report raw tokens
- Per-tool-call token breakdown within an agent — too granular, not available in hook data
- Modifying the
SubagentStart/SubagentStophook contract — we consume what Claude Code provides
Files Affected
scripts/hooks/subagent-start.sh— newscripts/hooks/subagent-stop.sh— new.claude/settings.json— hook configuration (or template forsequant init)src/commands/run.ts— print agent summary after runsrc/lib/log-writer.ts— read/aggregateagents.jsonldatasrc/commands/init.ts— auto-configure hooks on init.claude/skills/_shared/references/subagent-types.md— document hooks setup
References
- Claude Code hooks reference:
SubagentStartandSubagentStopevents SubagentStopinput fields:agent_id,agent_type,agent_transcript_path,last_assistant_message- Existing log infrastructure:
src/lib/log-writer.ts,.sequant/logs/ - Issue feat(#434): include QA verdict summary in sequant_logs output #481: QA verdict summary in sequant_logs (complementary — adds agent data alongside QA data)
/reflectskill consumessequant_logsoutput for workflow optimization
Activity
admarble commentedon Apr 6, 2026
→ PROCEED — Subagent lifecycle hooks for token cost visibility, clear ACs
spec → exec → qa · 19 ACs · -q (new hooks + log integration)
Chain after #483 (subagent-types.md, init.ts overlap with #484)
admarble commentedon Apr 8, 2026
Architecture Update — Event System Overlap
#504 (Typed workflow event system) introduces a
WorkflowEventEmitterwith events likephase_completedcarrying duration and metadata. The run summary display (AC-14 in this issue) could be implemented as an event listener under #504's architecture.What's NOT overlapping: The core of this issue — Claude Code
SubagentStart/SubagentStophooks, transcript file parsing,agents.jsonlformat, and shell-level hook integration — operates at the Claude Code hook layer, outside Sequant's internal event system. ~85% of this issue's scope is independent.Recommendation: If #504 lands first, wire the per-phase agent summary output as an event listener on
phase_completedrather than building a separate display path. The data collection mechanism (Claude Code hooks → transcript parsing →agents.jsonl) proceeds unchanged.