Skip to content

Add subagent lifecycle hooks for token cost visibility and diagnostics #486

Open

Description

@admarble

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:

  1. Diagnose expensive runs — "Why did this run cost $4?" requires reading full transcripts
  2. Tune configuration — Should I use effort: low? Is maxTurns: 15 too generous or too tight? No data to inform the decision
  3. 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
  • entire logs 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: SubagentStart hook configured in .claude/settings.local.json (or project settings) that logs: timestamp, agent_id, agent_type, issue number (from SEQUANT_ISSUE env 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: SubagentStop hook 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_path for 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: phase field populated from SEQUANT_PHASE env var (spec/exec/qa/test/loop)
  • AC-10: max_turns_hit derived from transcript content (detects turn-cap termination)

4. Integration with sequant_logs (P1)

  • AC-11: sequant_logs output includes agent summary section: total agents spawned, total agent tokens, breakdown by phase
  • AC-12: Agent data is read from .sequant/logs/agents.jsonl during log aggregation
  • AC-13: If agents.jsonl doesn't exist (hooks not configured), the agent summary section is omitted gracefully

5. Cost breakdown report (P1)

  • AC-14: After sequant run completes, 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.md explains 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 filtering
  • agent_transcript_path — path to the subagent's transcript file
  • last_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.jsonl

Correlation 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 jq is 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_logs skips agent summary
  • If /tmp start 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/SubagentStop hook contract — we consume what Claude Code provides

Files Affected

  • scripts/hooks/subagent-start.sh — new
  • scripts/hooks/subagent-stop.sh — new
  • .claude/settings.json — hook configuration (or template for sequant init)
  • src/commands/run.ts — print agent summary after run
  • src/lib/log-writer.ts — read/aggregate agents.jsonl data
  • src/commands/init.ts — auto-configure hooks on init
  • .claude/skills/_shared/references/subagent-types.md — document hooks setup

References

  • Claude Code hooks reference: SubagentStart and SubagentStop events
  • SubagentStop input 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)
  • /reflect skill consumes sequant_logs output for workflow optimization

Activity

  1. added
    enhancement
    planned
    multi-agent
    on Apr 5, 2026
  2. admarble commented on Apr 6, 2026

    @admarble
    ContributorAuthor

    → 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)

  3. admarble commented on Apr 8, 2026

    @admarble
    ContributorAuthor

    Architecture Update — Event System Overlap

    #504 (Typed workflow event system) introduces a WorkflowEventEmitter with events like phase_completed carrying 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/SubagentStop hooks, transcript file parsing, agents.jsonl format, 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_completed rather than building a separate display path. The data collection mechanism (Claude Code hooks → transcript parsing → agents.jsonl) proceeds unchanged.

  4. added
    backlog
    on Apr 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    backlogenhancementmulti-agentplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions