summarizeUsage function

Map<String, Object?> summarizeUsage(
  1. List<Map<String, Object?>> rows, {
  2. int topTransitions = 15,
})

Aggregates tool-call rows, ordered by correlation_id then id, into per-tool stats, the outcome-tagged tool-to-next-tool transitions, and self-correction rates; tokens come from estimated_tokens or else result_bytes.

Implementation

Map<String, Object?> summarizeUsage(List<Map<String, Object?>> rows, {int topTransitions = 15}) {
  final perTool = <String, _ToolAgg>{};
  final transitions = <String, int>{};
  final selfCorr = <String, List<int>>{};
  final turns = <String>{};
  String? prevCorr;
  String? prevTool;
  var prevOutcome = 'ok';
  String? prevErrorKind;

  for (final r in rows) {
    final corr = (r['correlation_id'] as String?) ?? '';
    final tool = (r['tool'] as String?) ?? '?';
    final outcome = (r['outcome'] as String?) ?? 'ok';
    final errorKind = r['error_kind'] as String?;
    final bytes = r['result_bytes'] as int?;
    turns.add(corr);
    perTool.putIfAbsent(tool, () => _ToolAgg(tool)).add(
          outcome,
          r['duration_ms'] as int?,
          bytes,
          (r['estimated_tokens'] as int?) ?? (bytes == null ? null : estimateTokens(bytes)),
          errorKind,
          (r['degraded'] as int? ?? 0) != 0,
        );
    if (prevCorr == corr && prevTool != null) {
      final key = '$prevTool|$prevOutcome|$tool';
      transitions[key] = (transitions[key] ?? 0) + 1;
      final signal = prevOutcome == 'error' ? (prevErrorKind ?? 'error') : (prevOutcome == 'empty' ? 'empty' : null);
      if (signal != null) {
        final agg = selfCorr.putIfAbsent('$prevTool|$signal', () => [0, 0]);
        agg[0]++;
        if (outcome == 'ok') agg[1]++;
      }
    }
    prevCorr = corr;
    prevTool = tool;
    prevOutcome = outcome;
    prevErrorKind = errorKind;
  }

  final toolsOut = perTool.values.map((a) => a.toJson()).toList()
    ..sort((a, b) => (b['count'] as int).compareTo(a['count'] as int));
  final transOut = transitions.entries.map((e) {
    final parts = e.key.split('|');
    return {'from': parts[0], 'fromOutcome': parts[1], 'to': parts[2], 'count': e.value};
  }).toList()
    ..sort((a, b) => (b['count'] as int).compareTo(a['count'] as int));
  final selfCorrOut = selfCorr.entries.map((e) {
    final parts = e.key.split('|');
    final occ = e.value[0];
    final rec = e.value[1];
    return {
      'tool': parts[0],
      'signal': parts[1],
      'occurrences': occ,
      'recovered': rec,
      'recoveryRate': occ == 0 ? 0.0 : _rate(rec, occ),
    };
  }).toList()
    ..sort((a, b) => (b['occurrences'] as int).compareTo(a['occurrences'] as int));

  final totalTokens = perTool.values.fold<int>(0, (s, a) => s + a.tokensSum);
  return {
    'totalEvents': rows.length,
    'totalTurns': turns.length,
    if (totalTokens > 0) 'totalEstimatedTokens': totalTokens,
    'tools': toolsOut,
    'transitions': transOut.take(topTransitions).toList(),
    if (selfCorrOut.isNotEmpty) 'selfCorrection': selfCorrOut,
  };
}