Skip to content

Improve pipeline observability: file tracking, git SHA, diff stats, token usage #278

Closed

Description

@admarble

Summary

Our run logs have good macro-level observability (phase timing, success/failure, QA verdicts) but several gaps that would significantly improve debuggability and user insight. All changes below are additive — new optional fields on existing schemas with backward-compatible defaults.


1. Consistently populate filesModified in phase logs

Problem: PhaseLog.filesModified exists in run-log-schema.ts:89 but is never populated. The completePhaseLog() helper at line 249 accepts an options object but filesModified isn't passed from the caller in run.ts:2484-2501.

Implementation:

  • In run.ts, after executePhase() returns and before createPhaseLogFromTiming(), run:
    git diff --name-only main...HEAD
    
    in the issue's worktree directory (available via worktreePath).
  • For the first phase of an issue, diff against the branch point. For subsequent phases, diff against main...HEAD (cumulative).
  • Pass the resulting string array as filesModified in the options to createPhaseLogFromTiming().
  • The createPhaseLogFromTiming() function at run-log-schema.ts:266 already accepts options — add filesModified?: string[] to the options type and pass it through to the PhaseLog.

Files to change:

  • src/lib/workflow/run-log-schema.ts — add filesModified to createPhaseLogFromTiming options type
  • src/commands/run.ts ~line 2484 — capture git diff and pass to phase log creation

2. Capture git commit SHA in run logs

Problem: No way to tie a run log entry to a specific commit state.

Implementation:

  • Add to RunLogSchema (run-log-schema.ts:157):
    startCommit: z.string().optional(),  // SHA at run start
    endCommit: z.string().optional(),    // SHA at run end
  • Add to PhaseLog (run-log-schema.ts:71):
    commitHash: z.string().optional(),   // SHA after phase completes
  • Capture via git rev-parse HEAD in the worktree:
    • At LogWriter.initialize() — set startCommit on the run log
    • At each createPhaseLogFromTiming() call — set commitHash
    • At LogWriter.finalize() — set endCommit on the run log
  • Update createEmptyRunLog() at line 204 and finalizeRunLog() at line 283 to accept/include these fields.

Files to change:

  • src/lib/workflow/run-log-schema.ts — schema additions
  • src/lib/workflow/log-writer.ts — capture SHA at initialize/finalize
  • src/commands/run.ts ~line 2484 — capture SHA per phase

3. Add per-file diff stats to phase logs

Problem: Metrics only have aggregate filesChanged and linesAdded (metrics-schema.ts:48-59). No per-file breakdown exists anywhere.

Implementation:

  • Add new Zod schema in run-log-schema.ts:
    const FileDiffStatSchema = z.object({
      path: z.string(),
      additions: z.number(),
      deletions: z.number(),
      status: z.enum(["added", "modified", "deleted", "renamed"]),
    });
  • Add to PhaseLog:
    fileDiffStats: z.array(FileDiffStatSchema).optional(),
  • Capture via git diff --numstat main...HEAD in the worktree (same timing as filesModified above — single git call can populate both).
  • Parse numstat output format: <additions>\t<deletions>\t<filepath> per line.
  • Determine status from git diff --name-status main...HEAD: A=added, M=modified, D=deleted, R=renamed.
  • Create a shared utility function (e.g., getGitDiffStats(worktreePath, baseBranch)) that returns both filesModified and fileDiffStats in one call to avoid redundant git operations.

Files to change:

  • src/lib/workflow/run-log-schema.ts — new FileDiffStatSchema, add field to PhaseLog
  • src/lib/workflow/run-log-schema.ts — update createPhaseLogFromTiming options
  • src/commands/run.ts ~line 2484 — call utility, pass results
  • New utility: src/lib/workflow/git-diff-utils.ts — getGitDiffStats() function

4. Token usage tracking via transcript parsing

Problem: MetricRun.metrics.tokensUsed (metrics-schema.ts:49) is always 0 (hardcoded at run.ts:2017).

Approach: Claude Code passes transcript_path (a JSONL file) to every hook. The ccusage project confirms these files contain per-message token data. A SessionEnd hook can parse the transcript and write token totals to a known location that run.ts reads before recording metrics.

Implementation:

A. Hook script — .claude/hooks/capture-tokens.sh:

#!/bin/bash
# SessionEnd hook: parse transcript JSONL for token usage
INPUT=$(cat)
TRANSCRIPT=$(echo "$INPUT" | jq -r '.transcript_path')
SESSION_ID=$(echo "$INPUT" | jq -r '.session_id')

if [ -z "$TRANSCRIPT" ] || [ ! -f "$TRANSCRIPT" ]; then
  exit 0
fi

# Sum token fields from JSONL messages
# Fields per ccusage: input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens
TOTALS=$(cat "$TRANSCRIPT" | jq -s '
  [.[] | .usage // empty] |
  {
    input_tokens: (map(.input_tokens // 0) | add // 0),
    output_tokens: (map(.output_tokens // 0) | add // 0),
    cache_creation_tokens: (map(.cache_creation_input_tokens // 0) | add // 0),
    cache_read_tokens: (map(.cache_read_input_tokens // 0) | add // 0)
  }
')

# Write to known location for sequant to pick up
TOKEN_FILE=".sequant/.token-usage-${SESSION_ID}.json"
echo "$TOTALS" > "$TOKEN_FILE"
exit 0

B. Hook registration — .claude/settings.json (or .claude/settings.local.json):

{
  "hooks": {
    "SessionEnd": [
      {
        "hooks": [{
          "type": "command",
          "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/capture-tokens.sh"
        }]
      }
    ]
  }
}

C. Sequant consumption — In run.ts at ~line 2008 before metricsWriter.recordRun():

  • Look for .sequant/.token-usage-*.json files
  • Sum token values across session files (a run may spawn multiple sessions)
  • Pass total to metrics.tokensUsed
  • Clean up the temp files after reading

D. Schema enhancement — Optionally expand RunMetrics in metrics-schema.ts:

tokensUsed: z.number(),           // total (keep for backward compat)
inputTokens: z.number().optional(),
outputTokens: z.number().optional(),
cacheTokens: z.number().optional(),

Limitation: This gives per-run totals, not per-phase. Per-phase would require a Stop hook (fires each time Claude finishes responding) with phase-aware logic, which is significantly more complex. Start with per-run totals.

Files to change:

  • New: .claude/hooks/capture-tokens.sh
  • .claude/settings.json or .claude/settings.local.json — hook registration
  • src/lib/workflow/metrics-schema.ts — optional expanded token fields
  • src/commands/run.ts ~line 2008 — read token files, pass to recordRun

5. Persist cache hit/miss metrics

Problem: quality-checks.sh tracks cache status in a CACHE_STATUS associative array and prints a summary table to stdout (lines 560-605), but nothing is structured or logged.

Implementation:

  • At the end of quality-checks.sh (after line 597), emit a JSON summary to a known file:
    # Write structured cache metrics
    CACHE_JSON="{\"hits\":$hit_count,\"misses\":$miss_count,\"skipped\":$skip_count,\"checks\":{"
    first=true
    for check in "${!CACHE_STATUS[@]}"; do
      $first || CACHE_JSON+=","
      CACHE_JSON+="\"$check\":\"${CACHE_STATUS[$check]}\""
      first=false
    done
    CACHE_JSON+="}}"
    echo "$CACHE_JSON" > ".sequant/.cache/qa/cache-metrics.json"
  • In run.ts, after the QA phase completes, read .sequant/.cache/qa/cache-metrics.json if it exists.
  • Add to PhaseLog schema:
    cacheMetrics: z.object({
      hits: z.number(),
      misses: z.number(),
      skipped: z.number(),
    }).optional(),
  • Only populated for QA phases.

Files to change:

  • .claude/skills/qa/scripts/quality-checks.sh ~line 597 — write JSON file
  • templates/skills/qa/scripts/quality-checks.sh — same change (keep in sync)
  • src/lib/workflow/run-log-schema.ts — add cacheMetrics to PhaseLog
  • src/commands/run.ts — read cache metrics after QA phase, pass to phase log

Backward Compatibility

All new fields are z.___().optional() with no defaults required. Existing log files parse fine — Zod's .optional() treats missing fields as undefined. The version: 1 stays unchanged since these are additive optional fields, not breaking changes.


Acceptance Criteria

  • filesModified reliably populated in all phase logs via git diff --name-only
  • startCommit/endCommit on RunLog, commitHash on PhaseLog via git rev-parse HEAD
  • fileDiffStats array on PhaseLog via git diff --numstat + --name-status
  • Shared getGitDiffStats() utility avoids redundant git operations
  • Token capture hook parses transcript JSONL and writes to .sequant/.token-usage-*.json
  • run.ts reads token files and populates metrics.tokensUsed (no longer 0)
  • Cache metrics written as JSON by quality-checks.sh, read into QA phase logs
  • All new schema fields are optional (backward compatible with existing logs)
  • sequant logs displays new fields when present
  • sequant stats includes token usage in analytics output
  • Existing tests pass
  • New unit tests for getGitDiffStats() utility and token file parsing

Activity

  1. added
    auto-ready
    on Feb 16, 2026
  2. admarble commented on Feb 19, 2026

    @admarble
    ContributorAuthor

    📋 Spec Plan for #278

    Scope Assessment

    Metric Value Status
    Feature count 5 ⚠️
    AC items 12 ⚠️
    Directory spread 4 ⚠️

    Verdict: ⚠️ SCOPE_WARNING - Multiple features bundled but well-defined. Proceeding with quality loop enabled.

    Suggested Non-Goals:

    • Per-phase token tracking (deferred - would require Stop hook complexity)
    • Historical log migration (existing logs remain valid)
    • Real-time dashboard updates

    Acceptance Criteria with Verification

    AC Description Verification
    AC-1 filesModified populated via git diff --name-only Integration Test
    AC-2 startCommit/endCommit/commitHash via git rev-parse HEAD Integration Test
    AC-3 fileDiffStats array via git diff --numstat + --name-status Unit Test
    AC-4 Shared getGitDiffStats() utility (avoid redundant git ops) Unit Test
    AC-5 Token capture hook writes .sequant/.token-usage-*.json Integration Test
    AC-6 run.ts reads token files, populates metrics.tokensUsed Integration Test
    AC-7 Cache metrics JSON from quality-checks.sh into QA phase logs Integration Test
    AC-8 All new schema fields optional (backward compatible) Unit Test
    AC-9 sequant logs displays new fields Manual Test
    AC-10 sequant stats includes token usage Manual Test
    AC-11 Existing tests pass Integration Test
    AC-12 New unit tests for utilities Unit Test

    Implementation Plan

    Phase 1: Schema Extensions

    • Add FileDiffStatSchema, cacheMetrics to PhaseLogSchema
    • Add commitHash to PhaseLog, startCommit/endCommit to RunLog
    • Add token breakdown fields to RunMetrics

    Phase 2: Git Diff Utility

    • Create src/lib/workflow/git-diff-utils.ts
    • getGitDiffStats(worktreePath, baseBranch) returns {filesModified, fileDiffStats}
    • Unit tests for parsing edge cases

    Phase 3: Token Capture Hook

    • Create .claude/hooks/capture-tokens.sh (SessionEnd hook)
    • Create token reader utility in src/lib/workflow/token-utils.ts

    Phase 4: Cache Metrics Persistence

    • Update quality-checks.sh to emit JSON to .sequant/.cache/qa/cache-metrics.json
    • Sync changes to templates/skills/qa/scripts/

    Phase 5: Run.ts Integration

    • Call getGitDiffStats() after phase execution
    • Capture commit SHA per phase
    • Read cache metrics for QA phase
    • Read token files before metrics recording

    Phase 6: LogWriter Updates

    • Capture startCommit in initialize()
    • Capture endCommit in finalize()

    Phase 7: Display Commands

    • Update sequant logs to show new fields
    • Update sequant stats to include token analytics

    Files to Change

    File Changes
    src/lib/workflow/run-log-schema.ts Schema additions
    src/lib/workflow/metrics-schema.ts Token breakdown fields
    src/lib/workflow/git-diff-utils.ts New - Git diff utility
    src/lib/workflow/token-utils.ts New - Token file reader
    src/lib/workflow/log-writer.ts Commit SHA capture
    src/commands/run.ts Integration points
    src/commands/logs.ts Display new fields
    src/commands/stats.ts Token analytics
    .claude/hooks/capture-tokens.sh New - SessionEnd hook
    .claude/skills/qa/scripts/quality-checks.sh Cache metrics JSON
    templates/skills/qa/scripts/quality-checks.sh Keep in sync

    Open Questions

    1. Hook registration: Should token hook be in .claude/settings.json (committed) or .claude/settings.local.json (user-specific)?

      • Recommendation: .claude/settings.local.json with setup docs
    2. LogWriter API: Pass worktree path to initialize() or capture SHA in run.ts?

      • Recommendation: Capture in run.ts, pass to LogWriter methods

    Recommended Workflow

    spec → testgen → exec → qa
    Quality Loop: enabled (auto-enabled due to scope)
    

    Assumptions to Validate

    • Claude Code transcript JSONL contains .usage objects with token fields
    • Git commands work consistently in worktree context
    • Hook registration in settings.local.json doesn't conflict with existing hooks
  3. added
    planned
    on Feb 19, 2026
  4. admarble commented on Feb 19, 2026

    @admarble
    ContributorAuthor

    🧪 Test Stubs Generated for Issue #278

    Summary

    AC Verification Happy Path Failure Paths File
    AC-1 Integration 5 tests 6 error scenarios observability.integration.test.ts
    AC-2 Integration 5 tests 6 error scenarios observability.integration.test.ts
    AC-3 Unit Test 7 tests 4 error cases git-diff-utils.test.ts
    AC-4 Unit Test 8 tests 7 error cases git-diff-utils.test.ts
    AC-5 Integration 5 tests 4 error scenarios observability.integration.test.ts
    AC-6 Integration 5 tests 4 error scenarios observability.integration.test.ts
    AC-7 Integration 5 tests 3 error scenarios observability.integration.test.ts
    AC-8 Unit Test 20 tests 8 error cases schema-backward-compat.test.ts
    AC-9 Manual Test — — See checklist below
    AC-10 Manual Test — — See checklist below
    AC-11 Integration 4 tests — observability.integration.test.ts
    AC-12 Unit Test 12 tests 8 error cases token-utils.test.ts

    Total: ~130 test stubs across 4 test files


    Unit Test Stubs

    src/lib/workflow/git-diff-utils.test.ts (AC-3, AC-4)

    • parseFileDiffStats(): 7 happy path + 10 edge cases + 4 error handling
    • getGitDiffStats(): 8 happy path + 7 edge cases + 7 error handling + 5 integration
    • Type validation: 8 tests
    • Performance optimization: 4 tests

    src/lib/workflow/token-utils.test.ts (AC-5, AC-6, AC-12)

    • parseTokenJsonFile(): 7 happy path + 5 edge cases + 5 error handling
    • readTokenUsageFiles(): 6 happy path + 5 error handling
    • aggregateTokenUsage(): 9 happy path + 3 edge cases
    • populateMetricsTokensUsed(): 4 tests
    • cleanupTokenFiles(): 4 tests
    • Type safety & utilities: 12 tests

    src/lib/workflow/schema-backward-compat.test.ts (AC-8)

    • RunLogSchema backward compat: 16 tests
    • MetricsSchema backward compat: 14 tests
    • Cross-schema scenarios: 12 tests

    Integration Test Stubs

    src/lib/workflow/observability.integration.test.ts (AC-1, AC-2, AC-5, AC-6, AC-7, AC-11)

    • Sandbox isolation with unique temp directories per test group
    • Happy path, error scenarios, and assumption validation for each AC

    Manual Test Checklists

    AC-9: sequant logs displays new fields

    Prerequisites

    • Run completed with observability features enabled
    • Run log contains filesModified, commitHash, fileDiffStats, cacheMetrics

    Test Steps

    1. Setup: Complete a run with: npx sequant run <issue>
    2. Action: Execute: npx sequant logs
    3. Verify: Check output displays new fields

    Expected Results

    • filesModified array displayed per phase
    • commitHash SHA displayed per phase
    • fileDiffStats table with additions/deletions/status
    • cacheMetrics (hits/misses/skipped) for QA phase
    • startCommit and endCommit displayed at run level

    Error Handling Verification

    • Missing fields show as "—" or are omitted cleanly
    • Large fileDiffStats arrays truncated appropriately
    • Invalid data doesn't crash command

    AC-10: sequant stats includes token usage

    Prerequisites

    • Token capture hook registered in .claude/settings.local.json
    • At least one run completed with token files generated

    Test Steps

    1. Setup: Ensure .sequant/.token-usage-*.json files exist
    2. Action: Execute: npx sequant stats
    3. Verify: Check analytics output

    Expected Results

    • tokensUsed total displayed in run analytics
    • inputTokens breakdown shown (if available)
    • outputTokens breakdown shown (if available)
    • cacheTokens breakdown shown (if available)
    • Token usage appears in aggregate statistics

    Error Handling Verification

    • Zero token usage displayed correctly
    • Missing token data doesn't crash command
    • Large token counts formatted appropriately

    Assumptions to Validate Before Implementation

    • Claude Code transcript JSONL contains .usage objects with token fields
    • Git commands work consistently in worktree context
    • Hook registration in settings.local.json doesn't conflict with existing hooks
    • jq is available for token hook JSON parsing

    Next Steps

    1. Implement test stubs (replace throw new Error(...) with actual test logic)
    2. Run /exec 278 to implement the feature
    3. Verify tests pass with npm test
    4. Manual testing using checklists above

    Generated with Claude Code

  5. added a commit that references this issue on Feb 20, 2026
  6. admarble commented on Feb 20, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #278
    Status: READY_FOR_MERGE
    PR: #303

    AC Coverage: 12/12 met

    AC Description Status
    AC-1 filesModified populated in phase logs ✅ MET
    AC-2 startCommit/endCommit + commitHash ✅ MET
    AC-3 fileDiffStats per-file breakdown ✅ MET
    AC-4 Shared getGitDiffStats() utility ✅ MET
    AC-5 Token capture hook + parsing ✅ MET
    AC-6 run.ts reads token files, populates metrics ✅ MET
    AC-7 Cache metrics in QA phase logs ✅ MET
    AC-8 All fields optional (backward compatible) ✅ MET
    AC-9 sequant logs displays new fields ✅ MET
    AC-10 sequant stats includes token analytics ✅ MET
    AC-11 Existing tests pass ✅ MET
    AC-12 New unit tests for utilities ✅ MET

    Quality Metrics

    • Tests: 34 new (10 git-diff-utils + 24 token-utils), all passing
    • Build: Clean
    • Type issues: 0
    • Files changed: 13 (+1472/-11)

    Iterations

    Phase Iterations Status
    Spec 1/1 Complete (prior)
    Exec 1/1 Complete
    QA 1/2 Complete

    Verdict: READY_FOR_MERGE

  7. added a commit that references this issue on Feb 20, 2026
  8. added a commit that references this issue on Jun 23, 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

    auto-readyplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions