Skip to content

Data-driven workflow optimization: systematic analysis of run logs and conversation data #437

Closed

Description

@admarble

Problem

Sequant has accumulated significant operational data from dogfooding — 81 structured run logs, 20KB of aggregated metrics, 148 Claude Code conversation transcripts (164MB), and live state/GitHub data — but no systematic process for mining this data to identify optimization opportunities, complexity hotspots, or workflow inefficiencies.

The existing sequant stats command (770 LOC) already provides solid aggregate analytics — success/failure rates, phase duration averages, token breakdown, chain-mode vs single-issue comparison, and auto-generated insights. The existing /reflect skill provides per-run observations. The /improve skill focuses on code patterns. What's missing is cross-run trend analysis, failure forensics, and a structured process for turning data into workflow improvements.

What Already Exists

Before building anything new, acknowledge the existing analytics surface:

Tool What It Does Gap
sequant stats Success rates, phase durations, token usage, insights, CSV/JSON export No temporal trends, no per-issue-type segmentation, no QA verdict analysis
sequant stats --json Machine-readable aggregate output Could pipe directly into context for analysis — may not need new tooling
run-reflect.ts Per-run timing patterns, phase mismatches, improvement suggestions Single-run only, no cross-run patterns
/reflect skill Session-level workflow analysis Conversation-scoped, no historical data
sequant logs View individual run details Display-focused, not analytical

Step zero of this issue is running sequant stats --json and assessing whether the gaps are worth filling.

Strategy

Phase A: Investigation (No Code)

The goal is to look at the data we have, establish baselines, and let findings drive decisions. No tooling until we know what's valuable.

A1: Baseline Establishment

Run sequant stats --json and document current baselines:

  • Overall success rate
  • Average duration per phase
  • Token cost per run
  • Chain mode vs single issue performance
  • Failure rate and common failure patterns

These baselines become the reference point for all future measurement. Without them, we can't tell if changes help.

A2: Bulk Log Analysis

Load all 81 run logs into a conversation. Token budget reality check: 620KB of JSON is ~150-200K tokens (not 50K — JSON averages 3-4 chars/token), which is 15-20% of the context window. Still feasible, but be precise.

Questions to answer, in priority order:

Temporal trends (most basic, currently missing from stats):

  • Are success rates improving, declining, or flat over the Jan 9 → Mar 25 window?
  • Are phase durations trending down as skills improve?
  • Is token cost per issue decreasing?

Phase-level analysis:

  • What's the first-pass QA rate (QA passes without quality loop)? stats tracks overall success but not QA-specific first-pass rate.
  • Which phases fail most often, and is it the phase's fault or the preceding phase's output?
  • Is spec duration correlated with issue complexity, or is it constant regardless? (run-reflect.ts checks this per-run; we need it cross-run)

Segmentation (currently missing from stats):

  • Break all metrics by: issue labels, lines changed, number of AC items, single vs batch, flags used
  • Which segments have the worst outcomes?
  • Are there issue characteristics that predict failure?

Quality loop effectiveness:

  • When quality loop triggers, how often does iteration 2 fix the issue? Iteration 3?
  • What's the token cost of loop iterations vs just re-running from scratch?

Expected output: Baselines documented, top 3-5 optimization targets ranked by impact, and hypotheses that emerged from the data (not pre-assumed).

A3: Failure Forensics

Identify all runs where status: "failure" or verdict: "AC_NOT_MET". For each:

  1. Examine the run log for phase-level detail
  2. Categorize the failure mode:
    • Tooling failure (build error, test infrastructure, worktree issue)
    • Wrong approach (agent took fundamentally wrong path)
    • Unclear AC (spec produced ambiguous criteria)
    • Scope overflow (changes exceeded issue boundaries)
    • Timeout (agent was making progress but ran out of time)
    • Skill prompt gap (skill instructions didn't cover this case)
  3. Count frequency of each category
  4. For the top 2-3 categories, identify specific fixes

Note on conversation logs: The 164MB of .jsonl transcripts in ~/.claude/projects/ could provide deeper forensics (exact tool call sequences, error messages, agent reasoning). However:

  • These are Claude Code's internal format, not a Sequant data source
  • The schema isn't documented or stable
  • 164MB ≈ 40M tokens — 40x the context window, requires selective loading
  • Not portable to Sequant users — only usable for internal dogfooding

Conversation log analysis should be treated as an internal-only supplement, not a product feature. For portable analysis, only run logs and metrics are available.

A4: Decision Framework

For each finding from A2/A3, define what action it implies:

Finding Pattern Action Type Decision Maker
Phase X adds no value for issue type Y Change default phase mapping in phase-mapper.ts Code change
Skill prompt causes consistent failure mode Update SKILL.md in all 3 directories Prompt change
Quality loop iteration N has diminishing returns Adjust maxIterations default or add early-exit logic Config + code
Success rate differs by 20%+ between segments Surface in stats insights to guide users Stats enhancement
Specific error accounts for >10% of failures Fix the root cause directly Bug fix

This prevents the common failure mode of "we analyzed the data, found interesting things, and then did nothing."

Phase B: Targeted Tooling (Only If A Reveals Gaps)

Build only what the investigation proves is needed. Likely candidates based on known stats gaps:

B1: Fill stats Gaps

Specific enhancements that stats.ts doesn't currently have:

  • Temporal trends — success rate, duration, cost over time (weekly/monthly buckets)
  • Per-issue-type segmentation — break metrics by label (bug vs feature vs refactor)
  • First-pass QA rate — QA pass rate without quality loop (distinct from overall success)
  • QA verdict distribution — READY_FOR_MERGE vs AC_MET_BUT_NOT_A_PLUS vs AC_NOT_MET counts

These are additive to the existing 770 LOC, not a rewrite.

B2: Metrics Extraction for Context Loading

If manual context-loading proves valuable in Phase A, formalize it:

  • Script that concatenates run logs into a context-loadable summary format
  • One row per issue-phase, not per run (more granular than current CSV export)
  • Include fields that current CSV omits: verdict, loop iterations, labels, lines changed

This may just be an enhancement to sequant stats --csv rather than a new script.

B3: /analyze Skill (Evaluate After A)

A skill that automates the Tier 1 analysis from Phase A. Architectural constraint: skills can't efficiently read 81 files. Viable approaches:

  1. Preprocessing: sequant stats --json --detailed produces a single JSON blob, skill reads one file
  2. Pipe approach: Skill instructions say "run sequant stats --json via Bash, then analyze the output"
  3. MCP resource: New sequant://analytics resource that returns pre-computed analysis

Decide which approach after Phase A reveals what analysis is actually valuable. Don't build the skill speculatively.

Context Window Budget (Corrected)

Analysis What to Load Actual Token Estimate
Run performance audit All 81 run logs (620KB JSON) ~150-200K (15-20%)
Failure deep-dive 5-10 failed run logs + notes ~30-50K (3-5%)
Stats JSON output sequant stats --json ~5-10K (<1%)
Skill prompt audit All 18 SKILL.md files ~50-80K (5-8%)
Conversation log (single) One full /fullsolve transcript ~100-300K (10-30%)
Conversation logs (selective) 5-10 failed run transcripts ~200-500K (20-50%)

Key constraint: Conversation logs (~40M tokens total) cannot be bulk-loaded. Must be highly selective — pick specific sessions by run ID correlation.

What's Portable for Sequant Users

Only data sources that Sequant controls are portable:

Portable (ship it) Internal Only (dogfooding)
Run logs (.sequant/logs/) Conversation transcripts (~/.claude/)
Metrics (.sequant/metrics.json) Claude Code session data
State (.sequant/state.json) Internal usage patterns
GitHub data (issues, PRs, comments)
sequant stats output

Any analysis tool we build should work exclusively with portable data sources. Conversation log mining is valuable for us but cannot be a product feature.

Acceptance Criteria

Investigation (Phase A)

  • Current sequant stats output reviewed and gaps documented
  • Baselines established from existing data (success rate, avg duration, cost per run)
  • Bulk log analysis completed: temporal trends, phase-level analysis, segmentation
  • First-pass QA rate calculated (not currently in stats)
  • All failed runs categorized by failure mode with frequency counts
  • Top 3-5 optimization targets identified and ranked by impact
  • Decision framework applied: each finding mapped to a specific action type

Tooling (Phase B — only after A is complete)

  • Specific stats enhancements identified from Phase A gaps (if any)
  • At least 2 actionable follow-up issues created from findings
  • Analysis approach documented so it can be repeated after workflow changes

Non-Goals

  • Building dashboards, data warehouses, or persistent analytics infrastructure
  • Telemetry or data collection that leaves the user's machine
  • Automated regression detection (future scope)
  • Benchmarking against other tools
  • Treating conversation log analysis as a portable/product feature
  • A/B testing (sample sizes are too small for statistical rigor; use qualitative before/after comparison instead)

Related

  • src/commands/stats.ts — existing 770 LOC analytics command (substantial overlap, must build on top of)
  • src/lib/workflow/run-reflect.ts — per-run reflection (subset of cross-run analysis)
  • /reflect skill — session-level workflow analysis
  • /improve skill — code pattern analysis (complementary, different focus)
  • sequant_logs: include QA verdict summary in structured output #434 — QA verdict summary in logs (supports failure forensics)

Activity

  1. added
    enhancement
    roadmap
    on Mar 25, 2026
  2. admarble commented on Mar 25, 2026

    @admarble
    ContributorAuthor

    Spec Plan: #437 — Data-Driven Workflow Optimization

    AC Quality Check

    AC format uses nested markdown headings — parser didn't auto-extract. Manual extraction below. Quality assessment:

    • AC-1–AC-7 (Phase A): Investigation-oriented, all clear and testable via documented output
    • AC-4: "First-pass QA rate calculated" — clear and specific
    • AC-8: "Specific stats enhancements identified" — clear (conditional on Phase A)
    • AC-9: "At least 2 actionable follow-up issues created" — clear and verifiable

    No vague or unmeasurable AC items.


    Scope Assessment

    Non-Goals (from issue)

    • ✅ Building dashboards, data warehouses, or persistent analytics infrastructure
    • ✅ Telemetry or data collection that leaves the user's machine
    • ✅ Automated regression detection (future scope)
    • ✅ Benchmarking against other tools
    • ✅ Treating conversation log analysis as a portable/product feature
    • ✅ A/B testing
    Metric Value Status
    Feature count 2 (analysis + targeted tooling) ⚠️
    AC items 10 ⚠️
    Directory spread 2 (src/commands, scripts/) ✅

    Verdict: ⚠️ SCOPE_WARNING — 10 AC items across 2 phases, but Phase B is explicitly conditional on Phase A. The issue is well-structured with clear phase boundaries.


    Acceptance Criteria

    Phase A: Investigation

    AC-1: Current sequant stats output reviewed and gaps documented

    Verification Method: Manual Test

    • Given: sequant stats --json output
    • When: Compare against issue's gap table
    • Then: Document with specific examples of missing data (temporal trends, segmentation, QA verdicts)

    AC-2: Baselines established from existing data

    Verification Method: Integration Test

    • Given: 81 run logs + 38 metrics entries
    • When: Run analysis script
    • Then: Output includes: overall success rate, avg duration per phase, token cost per run, chain vs single performance, failure rate

    AC-3: Bulk log analysis completed (temporal trends, phase-level, segmentation)

    Verification Method: Integration Test

    • Given: All 81 run logs loaded
    • When: Analysis script computes temporal buckets and segmentation
    • Then: Output shows weekly/monthly trends, per-label breakdown, and phase correlation data

    AC-4: First-pass QA rate calculated

    Verification Method: Unit Test

    • Given: QA phase logs with verdict data (75 QA phases with verdicts)
    • When: Calculate rate of first QA pass (READY_FOR_MERGE on first attempt)
    • Then: Numeric rate output with issue-level detail

    AC-5: All failed runs categorized by failure mode

    Verification Method: Integration Test

    • Given: 29 failed runs with 69 phase failures
    • When: Categorize into: tooling failure, wrong approach, unclear AC, scope overflow, timeout, skill prompt gap, rate limit
    • Then: Frequency table with at least 3 distinct categories

    AC-6: Top 3-5 optimization targets identified and ranked by impact

    Verification Method: Manual Test

    • Given: Findings from AC-2 through AC-5
    • When: Rank by estimated impact (frequency × severity)
    • Then: Numbered list with rationale for each

    AC-7: Decision framework applied

    Verification Method: Manual Test

    • Given: Each finding from AC-2 through AC-6
    • When: Map to action type (code change, prompt change, config, stats enhancement, bug fix)
    • Then: Table matching issue's decision framework template

    Phase B: Tooling

    AC-8: Specific stats enhancements identified from Phase A gaps

    Verification Method: Integration Test

    • Given: Phase A findings
    • When: Determine which gaps warrant stats.ts enhancements
    • Then: List of specific enhancements with rationale (may be empty if gaps don't warrant tooling)

    AC-9: At least 2 actionable follow-up issues created

    Verification Method: Manual Test

    • Given: Optimization targets from AC-6
    • When: Create GitHub issues via gh issue create
    • Then: 2+ issues exist with clear scope, AC, and references to this analysis

    AC-10: Analysis approach documented so it can be repeated

    Verification Method: Manual Test

    • Given: Complete analysis pipeline
    • When: Document in docs/reference/ or as a repeatable script
    • Then: A new contributor could re-run the analysis after future workflow changes

    Implementation Plan

    Phase 1: Analysis Script (AC-1, AC-2, AC-3, AC-4, AC-5)

    Create scripts/analytics/analyze-runs.ts that:

    1. Loads all 81 run logs from .sequant/logs/
    2. Computes baselines: success rate, avg duration, cost per run
    3. Computes temporal trends in weekly buckets
    4. Calculates first-pass QA rate from verdict data
    5. Segments metrics by issue labels, LOC, AC count
    6. Categorizes all failures by mode (tooling vs approach vs AC vs timeout vs rate-limit)
    7. Outputs structured JSON report

    Key data points already known:

    • 456 total phases, 134 QA phases
    • QA verdicts: 49 READY_FOR_MERGE, 11 AC_MET_BUT_NOT_A_PLUS, 13 AC_NOT_MET, 2 NEEDS_VERIFICATION
    • Phase failures: qa=27, exec=27, spec=12, testgen=3
    • Most failures are generic "exit code 1" — need deeper categorization

    Phase 2: Findings Report (AC-6, AC-7)

    Synthesize analysis output into:

    1. Top 3-5 optimization targets ranked by impact
    2. Decision framework table mapping each finding to an action type
    3. Write report to docs/reference/workflow-analysis-2026-03.md

    Phase 3: Stats Enhancements (AC-8)

    Based on Phase A gaps, enhance stats.ts with:

    • --detailed flag for expanded analysis (temporal trends, QA verdicts, segmentation)
    • Add QA verdict distribution to standard output
    • Add first-pass QA rate metric

    Phase 4: Follow-up Issues + Documentation (AC-9, AC-10)

    1. Create 2+ follow-up issues from findings
    2. Document analysis approach as repeatable process

    Design Review

    1. Where does this logic belong? Analysis script in scripts/analytics/ (one-time investigation), with targeted enhancements to src/commands/stats.ts (durable tooling). Report in docs/reference/.

    2. What's the simplest correct approach? A TypeScript analysis script that loads all logs, computes everything in-memory, and outputs JSON. Stats enhancements are additive to the existing 770 LOC — no rewrite. Follow-up issues created via gh issue create.

    3. What existing pattern does this follow? Follows scripts/qa/*.ts pattern for one-off analysis scripts. Stats enhancements follow existing stats.ts patterns (AggregateStats interface, display functions).

    4. What would a senior reviewer challenge? (1) "Why a script vs just loading logs into a conversation?" — Script is repeatable (AC-10) and produces structured output for stats integration. (2) "Is the analysis script worth keeping long-term?" — Yes, it enables re-running after workflow changes per AC-10.


    Feature Quality Planning

    Completeness Check

    • All AC items have corresponding implementation steps
    • Integration: stats.ts (additive), run-log-schema (read-only)
    • No partial implementations planned
    • Data flow: logs → analysis script → JSON report → stats enhancements + follow-up issues

    Error Handling

    • Malformed log files: skip with warning (parseLogFile already handles this)
    • Empty logs directory: report "no data" gracefully
    • Missing verdict data: count as "no verdict" segment

    Code Quality

    • Types from existing RunLogSchema and MetricsSchema
    • Follows existing stats.ts patterns
    • No magic strings — use Phase type from schema

    Test Coverage Plan

    • Unit test for first-pass QA rate calculation
    • Unit test for failure categorization logic
    • Integration test for full analysis pipeline
    • Edge cases: empty logs, logs with no QA phases, logs with no failures

    Best Practices

    • Script logs analysis parameters and data range
    • No external dependencies — uses existing schemas
    • Documentation: analysis approach doc

    Derived ACs

    Source Derived AC Priority
    Test Coverage AC-11: Unit tests for analysis functions Medium

    Recommended Workflow

    Phases: spec → exec → qa
    Quality Loop: enabled (auto-enabled due to scope warning)
    Reasoning: Investigation + tooling issue, no UI components. Quality loop ensures analysis completeness.


    Label Review

    Current: enhancement, roadmap
    Recommended: enhancement, roadmap, cli
    Reason: Stats command is CLI-facing; analysis enhances CLI output
    Quality Loop: Auto-enabled due to scope warning

    → gh issue edit 437 --add-label cli

  3. added
    planned
    cli
    on Mar 25, 2026
  4. added a commit that references this issue on Mar 25, 2026
  5. admarble commented on Mar 25, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #437

    AC Coverage

    AC Description Status Notes
    AC-1 Stats output reviewed, gaps documented MET Analysis report documents all gaps vs current stats
    AC-2 Baselines established MET 68.3% success rate, 27m 52s avg duration, chain vs single comparison
    AC-3 Bulk log analysis (trends, phases, segments) MET Weekly buckets, per-phase durations, per-label segmentation
    AC-4 First-pass QA rate calculated MET 38.2% — computed from 134 QA phases grouped by issue
    AC-5 Failed runs categorized by failure mode MET 6 categories: tooling (60.6%), QA verdict, rate limit, timeout, unknown
    AC-6 Top 3-5 optimization targets identified MET 5 targets ranked by impact in report
    AC-7 Decision framework applied MET Each finding mapped to action type, priority, and effort
    AC-8 Stats enhancements identified MET --detailed flag adds QA verdicts, weekly trends, label segmentation
    AC-9 2+ follow-up issues created MET #447 (error capture), #448 (QA rate improvement)
    AC-10 Analysis approach documented MET Report includes "Repeatable Analysis Approach" section with commands
    AC-11 Unit tests for analysis functions MET 20 tests covering all analysis functions

    Coverage: 11/11 AC items fully met


    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 OK
    Files changed 7 OK
    Lines added +1377 OK (new script + enhancements)
    Lines deleted -26 OK

    Test Coverage Analysis

    Changed File Tier Has Tests? Test File
    scripts/analytics/analyze-runs.ts Standard Yes scripts/analytics/analyze-runs.test.ts
    src/commands/stats.ts Standard Yes src/commands/stats.test.ts
    bin/cli.ts Standard Yes (covered by stats.test.ts --detailed tests)
    docs/reference/workflow-analysis-2026-03.md Optional N/A Documentation
    CHANGELOG.md Optional N/A Metadata

    Coverage: 3/3 changed source files have corresponding tests


    CLI Registration Verification

    Interface Field Runtime Usage CLI Registered Status
    detailed options.detailed (stats.ts) --detailed in bin/cli.ts OK

    Verification Status: Passed


    Code Review

    Strengths:

    • Clean separation: analysis script for deep investigation, stats enhancement for CLI integration
    • Reuses existing RunLogSchema and patterns from stats.ts
    • Good test coverage: 7 tests for analysis script, 4 tests for --detailed flag, 9 existing tests still pass
    • QA first-pass rate computation correctly groups by issue and sorts by start time

    Issues found and fixed:

    • Unused type imports (IssueLog, QaVerdict, Phase) in analyze-runs.ts — fixed in follow-up commit

    Suggestions:

    • None blocking

    Smoke Test

    Test Command Result Notes
    Analysis script JSON npx tsx scripts/analytics/analyze-runs.ts --json Pass Valid JSON with all sections
    Analysis script human npx tsx scripts/analytics/analyze-runs.ts Pass Human-readable dashboard
    Stats --detailed help npx tsx bin/cli.ts stats --help Pass Flag visible in help output

    Smoke Test Status: Complete


    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists Found
    User-facing changes Yes (new CLI flag)
    [Unreleased] entry Present (2 entries for #437)
    Entry format Valid (starts with "Add", includes #437)

    Result: CHANGELOG requirements met


    Self-Evaluation

    • Verified working: Yes — ran analysis script against actual 82 logs, verified JSON output structure and human-readable display
    • Test efficacy: High — tests verify baselines, QA rate, failure categorization, label segmentation, and temporal trends with fixture data
    • Likely failure mode: Schema changes to RunLog could break the analysis script. Mitigated by using Zod schema validation (malformed logs are skipped).
    • Verdict confidence: High — all AC items verified with concrete evidence, smoke tests pass, no outstanding concerns

    Verdict: READY_FOR_MERGE

    All 11 AC items are met. Analysis script produces accurate findings from 82 run logs. Stats --detailed flag is properly wired from CLI to implementation. Tests cover all new code. Two actionable follow-up issues (#447, #448) created from the highest-impact findings.

    Documentation

    • CHANGELOG entry added
    • Analysis report written (docs/reference/workflow-analysis-2026-03.md)
    • Repeatable approach documented in report

    Next Steps

    1. Merge PR feat(#437): data-driven workflow analysis and detailed stats #450
    2. Work on follow-up Improve error capture for tooling failures (60% of all failures) #447 (error capture for tooling failures — highest impact)
    3. Work on follow-up Investigate and improve first-pass QA rate (currently 38%) #448 (improve first-pass QA rate)

    PR: #450

  6. added a commit that references this issue on Mar 25, 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

    clienhancementplannedroadmap

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions