Repository navigation
Description
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, afterexecutePhase()returns and beforecreatePhaseLogFromTiming(), run:in the issue's worktree directory (available viagit diff --name-only main...HEADworktreePath). - 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
filesModifiedin the options tocreatePhaseLogFromTiming(). - The
createPhaseLogFromTiming()function atrun-log-schema.ts:266already acceptsoptions— addfilesModified?: string[]to the options type and pass it through to the PhaseLog.
Files to change:
src/lib/workflow/run-log-schema.ts— addfilesModifiedtocreatePhaseLogFromTimingoptions typesrc/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 HEADin the worktree:- At
LogWriter.initialize()— setstartCommiton the run log - At each
createPhaseLogFromTiming()call — setcommitHash - At
LogWriter.finalize()— setendCommiton the run log
- At
- Update
createEmptyRunLog()at line 204 andfinalizeRunLog()at line 283 to accept/include these fields.
Files to change:
src/lib/workflow/run-log-schema.ts— schema additionssrc/lib/workflow/log-writer.ts— capture SHA at initialize/finalizesrc/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...HEADin the worktree (same timing asfilesModifiedabove — 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 bothfilesModifiedandfileDiffStatsin one call to avoid redundant git operations.
Files to change:
src/lib/workflow/run-log-schema.ts— newFileDiffStatSchema, add field toPhaseLogsrc/lib/workflow/run-log-schema.ts— updatecreatePhaseLogFromTimingoptionssrc/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 0B. 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-*.jsonfiles - 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.jsonor.claude/settings.local.json— hook registrationsrc/lib/workflow/metrics-schema.ts— optional expanded token fieldssrc/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.jsonif it exists. - Add to
PhaseLogschema: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 filetemplates/skills/qa/scripts/quality-checks.sh— same change (keep in sync)src/lib/workflow/run-log-schema.ts— addcacheMetricsto PhaseLogsrc/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
-
filesModifiedreliably populated in all phase logs viagit diff --name-only -
startCommit/endCommiton RunLog,commitHashon PhaseLog viagit rev-parse HEAD -
fileDiffStatsarray on PhaseLog viagit 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.tsreads token files and populatesmetrics.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 logsdisplays new fields when present -
sequant statsincludes token usage in analytics output - Existing tests pass
- New unit tests for
getGitDiffStats()utility and token file parsing
Activity
admarble commentedon Feb 19, 2026
📋 Spec Plan for #278
Scope Assessment
Verdict:⚠️ SCOPE_WARNING - Multiple features bundled but well-defined. Proceeding with quality loop enabled.
Suggested Non-Goals:
Acceptance Criteria with Verification
filesModifiedpopulated viagit diff --name-onlystartCommit/endCommit/commitHashviagit rev-parse HEADfileDiffStatsarray viagit diff --numstat+--name-statusgetGitDiffStats()utility (avoid redundant git ops).sequant/.token-usage-*.jsonrun.tsreads token files, populatesmetrics.tokensUsedquality-checks.shinto QA phase logssequant logsdisplays new fieldssequant statsincludes token usageImplementation Plan
Phase 1: Schema Extensions
FileDiffStatSchema,cacheMetricstoPhaseLogSchemacommitHashtoPhaseLog,startCommit/endCommittoRunLogRunMetricsPhase 2: Git Diff Utility
src/lib/workflow/git-diff-utils.tsgetGitDiffStats(worktreePath, baseBranch)returns{filesModified, fileDiffStats}Phase 3: Token Capture Hook
.claude/hooks/capture-tokens.sh(SessionEnd hook)src/lib/workflow/token-utils.tsPhase 4: Cache Metrics Persistence
quality-checks.shto emit JSON to.sequant/.cache/qa/cache-metrics.jsontemplates/skills/qa/scripts/Phase 5: Run.ts Integration
getGitDiffStats()after phase executionPhase 6: LogWriter Updates
startCommitininitialize()endCommitinfinalize()Phase 7: Display Commands
sequant logsto show new fieldssequant statsto include token analyticsFiles to Change
src/lib/workflow/run-log-schema.tssrc/lib/workflow/metrics-schema.tssrc/lib/workflow/git-diff-utils.tssrc/lib/workflow/token-utils.tssrc/lib/workflow/log-writer.tssrc/commands/run.tssrc/commands/logs.tssrc/commands/stats.ts.claude/hooks/capture-tokens.sh.claude/skills/qa/scripts/quality-checks.shtemplates/skills/qa/scripts/quality-checks.shOpen Questions
Hook registration: Should token hook be in
.claude/settings.json(committed) or.claude/settings.local.json(user-specific)?.claude/settings.local.jsonwith setup docsLogWriter API: Pass worktree path to
initialize()or capture SHA in run.ts?Recommended Workflow
Assumptions to Validate
.usageobjects with token fieldsadmarble commentedon Feb 19, 2026
🧪 Test Stubs Generated for Issue #278
Summary
observability.integration.test.tsobservability.integration.test.tsgit-diff-utils.test.tsgit-diff-utils.test.tsobservability.integration.test.tsobservability.integration.test.tsobservability.integration.test.tsschema-backward-compat.test.tsobservability.integration.test.tstoken-utils.test.tsTotal: ~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 handlinggetGitDiffStats(): 8 happy path + 7 edge cases + 7 error handling + 5 integrationsrc/lib/workflow/token-utils.test.ts(AC-5, AC-6, AC-12)parseTokenJsonFile(): 7 happy path + 5 edge cases + 5 error handlingreadTokenUsageFiles(): 6 happy path + 5 error handlingaggregateTokenUsage(): 9 happy path + 3 edge casespopulateMetricsTokensUsed(): 4 testscleanupTokenFiles(): 4 testssrc/lib/workflow/schema-backward-compat.test.ts(AC-8)Integration Test Stubs
src/lib/workflow/observability.integration.test.ts(AC-1, AC-2, AC-5, AC-6, AC-7, AC-11)Manual Test Checklists
AC-9:
sequant logsdisplays new fieldsPrerequisites
filesModified,commitHash,fileDiffStats,cacheMetricsTest Steps
npx sequant run <issue>npx sequant logsExpected Results
filesModifiedarray displayed per phasecommitHashSHA displayed per phasefileDiffStatstable with additions/deletions/statuscacheMetrics(hits/misses/skipped) for QA phasestartCommitandendCommitdisplayed at run levelError Handling Verification
AC-10:
sequant statsincludes token usagePrerequisites
.claude/settings.local.jsonTest Steps
.sequant/.token-usage-*.jsonfiles existnpx sequant statsExpected Results
tokensUsedtotal displayed in run analyticsinputTokensbreakdown shown (if available)outputTokensbreakdown shown (if available)cacheTokensbreakdown shown (if available)Error Handling Verification
Assumptions to Validate Before Implementation
.usageobjects with token fieldsNext Steps
throw new Error(...)with actual test logic)/exec 278to implement the featurenpm testGenerated with Claude Code
feat(#278): improve pipeline observability with file tracking, git SH…
admarble commentedon Feb 20, 2026
/fullsolve Complete
Issue: #278
Status: READY_FOR_MERGE
PR: #303
AC Coverage: 12/12 met
Quality Metrics
Iterations
Verdict: READY_FOR_MERGE
fix(#278): register SessionEnd hook for token usage capture
docs: update what-weve-built and changelog for #278
chore(#738): reconcile skill-mirror divergences (8 diverged, 10 missi…