Maestro icon indicating copy to clipboard operation
Maestro copied to clipboard

fix: reconcile Auto Run summary with cumulative session stats

Open pedramamini opened this issue 7 months ago • 3 comments

Summary

  • Auto Run summary now reconciles in-memory counters with persisted history entries, ensuring accurate cumulative stats (tasks, tokens, cost, duration) even when sessions span app restarts
  • Applied the fix to both the renderer (useBatchProcessor.ts) and CLI (batch-processor.ts) codepaths

Closes #734

Root Cause

In-memory cumulative counters (totalCompletedTasks, totalInputTokens, totalOutputTokens, totalCost) are initialized fresh each time startBatchRun is called. For long-running sessions that survive app restarts, manual stop/restart cycles, or process kills, the final "Auto Run stopped" summary only reflected stats from the most recent invocation — while all individual task history entries persisted on disk across restarts.

Fix

Before generating the final summary, read all persisted history entries for the session and compute cumulative totals from task entries (filtering out loop/session summary entries). Use Math.max(inMemory, historyDerived) to ensure the summary is accurate regardless of restart history. Falls back gracefully to in-memory counters if history read fails.

Test plan

  • [ ] Run an Auto Run session, let it complete naturally — summary should match in-memory counters (no regression)
  • [ ] Start an Auto Run, restart the app mid-session, resume the Auto Run, then stop — summary should reflect tasks from all invocations
  • [ ] Verify the summary entry in history shows correct cumulative tasks, tokens, cost, and duration
  • [ ] Run npm run lint and npm test — all pass

Summary by CodeRabbit

  • Bug Fixes

    • Auto Run summaries now reconcile metrics with persisted history to report accurate task completion counts, elapsed time, and costs, especially after session restarts.
  • Documentation

    • Updated multi-phase feature organization guidance to use flat directory structure instead of nested subdirectories.
  • Tests

    • Added comprehensive tests for history reconciliation behavior during Auto Run completion.

pedramamini avatar Apr 06 '26 02:04 pedramamini

Review Change Stack

📝 Walkthrough

Walkthrough

This PR reconciles in-memory Auto Run counters with persisted AUTO history entries by reading filtered task records, aggregating usage metrics and elapsed time, and applying Math.max comparisons to avoid decreasing totals. Changes span CLI batch processor, renderer hook finalization, and comprehensive test coverage.

Changes

Auto Run history reconciliation

Layer / File(s) Summary
Batch processor: reconciliation implementation and wiring
src/cli/services/batch-processor.ts
Import readHistory, introduce computeReconciledTotals() to read persisted AUTO entries for the session, locate the most recent prior "Auto Run " summary boundary, filter out non-task summaries (Loop, PR created, Auto Run entries), aggregate tasks count and sum usageStats/elapsedTimeMs, and conditionally update in-memory counters via Math.max; wrap in try/catch with warning fallback. Refactor createAutoRunSummary to accept reconciled totals and use them for final summary display; wire reconciliation call and use reconciled values for persisted history entry and complete event emission.
Renderer hook: finalization reconciliation
src/renderer/hooks/batch/useBatchProcessor.ts
Make totalElapsedMs mutable and add parallel reconciliation logic before final summary computation: read persisted history via window.maestro.history.getAll(), apply same boundary and filter rules, aggregate metrics, and apply Math.max to increase (not decrease) in-memory counters; swallow errors with warning log.
Tests: history reconciliation coverage
src/__tests__/cli/services/batch-processor.test.ts
Extend mocked storage module to include readHistory and set default mock to empty array. Add new runPlaybook - history reconciliation suite with helper functions for single-task runs and AUTO history entries; add tests for restart task/cost accumulation without prior summary, boundary enforcement to exclude tasks from prior completed runs, and readHistory exception handling with fallback to in-memory totals and logger.warn verification.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • RunMaestro/Maestro#752: Reconciliation in this PR depends on persisted AUTO history format and values, which PR #752 modifies via synopsis skipping and updated task_complete entry accounting.

Suggested labels

ready to merge

Poem

A session of loops, a week in the sand,
Now counts all the tasks across the full span.
No more lost in summaries—Math.max keeps score,
From persisted history, we remember it all once more. 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly describes the main objective: reconciling Auto Run summary totals with cumulative session stats across restarts, which is the core change across all modified files.
Linked Issues check ✅ Passed The PR fully addresses issue #734 by implementing history reconciliation to compute cumulative totals (tasks, duration, tokens, cost) across all session entries, excluding summaries and loop entries, with proper fallback handling.
Out of Scope Changes check ✅ Passed All changes align with the stated objectives: history reconciliation in batch-processor.ts and useBatchProcessor.ts, test coverage for reconciliation scenarios, and a single-line update to maestro-system-prompt.md documentation as part of scope.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • [ ] Create stacked PR
  • [ ] Commit on current branch
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Commit unit tests in branch 734-cumulative-autorun-summary-stats

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Apr 06 '26 02:04 coderabbitai[bot]

Greptile Summary

This PR fixes a real bug where Auto Run summary stats were reset to zero on app restart by reconciling in-memory counters against persisted history entries before writing the final summary. The fix is applied to both the renderer (useBatchProcessor.ts) and CLI (batch-processor.ts) codepaths, and the approach is sound for the restart scenario.

However, the reconciliation reads all history entries for the session without scoping them to the current Auto Run invocation by timestamp. This creates a regression for the more common case where a user runs Auto Run more than once on the same agent session: every subsequent run will absorb all prior task entries and report inflated task counts, token usage, and cost in its summary.

  • src/renderer/hooks/batch/useBatchProcessor.ts — New try/catch block calls window.maestro.history.getAll(session.cwd, sessionId) and applies Math.max reconciliation. Works correctly for the restart scenario but over-counts on repeat runs of the same agent session.
  • src/cli/services/batch-processor.ts — Identical logic via readHistory(undefined, session.id). Same flaw; both paths must be kept in sync.
  • docs/releases.md / src/prompts/maestro-system-prompt.md — Formatting and minor prose changes only; no functional impact.
  • Both catch blocks are empty, swallowing unexpected errors without logging — this conflicts with the project's Sentry-first error-handling guidelines in CLAUDE.md.

Confidence Score: 2/5

Not safe to merge as-is — the reconciliation logic will produce inflated Auto Run summaries for any session that has more than one completed Auto Run invocation

The intended fix (handling app-restart continuity) is correct in principle, but the implementation has a clear logic bug that regresses the more common case of running Auto Run multiple times on the same agent. The missing timestamp boundary means all prior task history is summed into every new summary. The fix is also duplicated across two code paths that must stay in sync.

src/renderer/hooks/batch/useBatchProcessor.ts and src/cli/services/batch-processor.ts — specifically the history filter predicate that lacks a batchStartTime lower bound

Important Files Changed

Filename Overview
src/renderer/hooks/batch/useBatchProcessor.ts Adds history-based stat reconciliation before the Auto Run final summary, but the unbounded history query (no timestamp fence) will overcount tasks/tokens/cost on any repeat run of the same agent session
src/cli/services/batch-processor.ts Mirrors the renderer reconciliation logic with the identical over-counting flaw — readHistory fetches all session entries with no timestamp boundary
docs/releases.md Whitespace and list-formatting adjustments to release notes only; no functional changes
src/prompts/maestro-system-prompt.md Minor prose update to the system prompt; no functional impact

Sequence Diagram

sequenceDiagram
    participant User
    participant BatchProcessor
    participant HistoryStore

    User->>BatchProcessor: Stop / complete Auto Run
    BatchProcessor->>HistoryStore: getAll(cwd, sessionId)
    HistoryStore-->>BatchProcessor: ALL entries for session (no timestamp bound)
    BatchProcessor->>BatchProcessor: filter to AUTO task entries
    Note over BatchProcessor: ⚠️ Includes entries from prior completed runs
    alt taskEntries.length > totalCompletedTasks
        BatchProcessor->>BatchProcessor: sum tokens/cost from ALL task entries
        BatchProcessor->>BatchProcessor: Math.max(inMemory, historyDerived)
        Note over BatchProcessor: Correct for restart scenario<br/>Overcounts for repeat-run scenario
    else
        BatchProcessor->>BatchProcessor: Use in-memory counters unchanged
    end
    BatchProcessor->>HistoryStore: addHistoryEntry(finalSummary)
    BatchProcessor-->>User: Show Auto Run summary

Reviews (1): Last reviewed commit: "style: format docs/releases.md with pret..." | Re-trigger Greptile

greptile-apps avatar Apr 06 '26 02:04 greptile-apps

Addressed the review feedback. Pushed two commits.

P1 - over-counting on repeat runs (greptile + greptile/coderabbit): Fixed in both the renderer (`useBatchProcessor.ts`) and CLI (`batch-processor.ts`) paths, but not via the suggested `e.timestamp < batchStartTime` filter - that approach doesn't actually fix the reported scenario. Run #1 (30 tasks) completes before run #2 starts, so all 30 entries still pre-date `batchStartTime` and get added back to run #2's in-memory count → still 50.

Instead, I scope the history scan to entries written after the most recent prior "Auto Run" summary entry. A completed or stopped run always ends with such a summary; an app restart / process kill does not. So this correctly spans restarts (the actual bug in #734) while excluding earlier completed runs on the same agent/session. Added CLI regression tests for both the restart-reconciliation case and the no-cross-run-overcount case.

Major - reconciled totals never reached the CLI `complete` event (coderabbit): Extracted a `computeReconciledTotals()` helper, called once, and fed it into both the persisted summary entry and the terminal `complete` JSONL event so resumed runs report cumulative stats to CLI/JSONL consumers.

P2 - silent catch blocks (greptile + coderabbit): Both fall-back catches now log (renderer `console.warn`, CLI `logger.warn` with `sessionId` context). Added a test asserting the warn-and-fallback path.

Out-of-scope docs churn (coderabbit pre-merge check): Reverted the `docs/releases.md` line-ending normalization entirely - it's an auto-generated file and net-zero now. That also moots the `FIle` typo and heading/bullet nits, which were all in that churned file.

Stale comment: The `maestro-system-prompt.md` multi-phase guidance comment is against a revision no longer in the diff - that file isn't part of this PR anymore.

Local: `tsc`, `eslint`, `prettier`, and the batch-processor unit suites pass.

pedramamini avatar Jun 13 '26 20:06 pedramamini