Repository navigation
feat: rewind fix — AI-powered session diagnosis and proxy request rewriting - #90
Conversation
…lumns The Python store was missing two v0.6 migrations that the Rust schema already had: `steps.tool_name` and `sessions.source`. This caused `get_steps()` to omit tool_name, which the upcoming `rewind fix` diagnosis engine needs to identify which tool calls failed. Changes: - Add v0.6 ALTER TABLE migrations matching Rust db.rs lines 301-304 - Add `tool_name` param to `create_step()` and column to `get_steps()` - Add tests for tool_name presence in step dicts Made-with: Cursor
LLM-powered diagnosis subprocess that analyzes failed agent sessions and returns structured output: root cause, failed step, fix type, fix params, and confidence level. Uses function calling to force structured output. Supports 5 fix types: swap_model, inject_system, adjust_temperature, retry_step (exploit non-determinism), and no_fix (agent code issue). Follows the exact subprocess protocol from llm_judge.py: stdin JSON, stdout JSON, 120s timeout, non-zero exit on config errors. Made-with: Cursor
Adds the `rewind fix <session>` command that analyzes a failed agent session and prints a structured diagnosis with root cause, suggested fix type, and confidence level. The command loads session data from the local store, assembles a diagnostic payload, and shells out to `python3 -m rewind_agent.fix` (same subprocess protocol as llm_judge). Supports: --step N (target specific step), --expected (soft failures), --json (machine output), --diagnosis-model. The --apply, --command, and --hypothesis flags are defined but stubbed for Phase 2-3. Made-with: Cursor
Adds RewriteConfig struct and apply_rewrites() to the proxy, enabling LLM request modification after the fork point during replay. Supports three rewrite types: - model swap (same-provider only; cross-provider swaps blocked) - system message injection (OpenAI role:system + Anthropic string/array) - temperature override Key design decisions from Santa Method review: - Provider detection uses model name, not body structure - Anthropic array-format system (for prompt caching) handled correctly - Content-Length header filtered from copy loop (reqwest recalculates) - Cross-provider model swaps log warning and skip (not silently fail) Includes 14 unit tests covering all rewrite paths and edge cases. Made-with: Cursor
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
- Add sys.exit(1) to Python catch-all exception handler so Rust CLI correctly surfaces unexpected diagnosis failures as errors (both reviewers flagged this independently) - Handle stdin write failure explicitly instead of silently swallowing with `let _` — kills child and reports payload size on pipe failure - Add try/except for json.loads of LLM function call arguments to produce a clear error when diagnosis model returns malformed output Made-with: Cursor
Completes Phase 3: the full diagnose → fork → replay-with-patch → score loop. Three modes now work: - `rewind fix latest` — diagnosis only (Phase 1, unchanged) - `rewind fix latest --apply` — diagnose, dry-run preview, fork, start proxy with rewrites, wait for Ctrl+C, print savings - `rewind fix latest --apply --command "python agent.py"` — fully automated: spawns agent with OPENAI_BASE_URL and ANTHROPIC_BASE_URL pointing at the patched proxy, waits for completion, prints savings Also implements: - `--hypothesis "swap_model:gpt-4o"` to skip diagnosis and directly test a fix theory (power user escape hatch) - Dry-run preview with y/N confirmation (skip with --yes) - Direct-mode session guard (--apply requires proxy-recorded sessions) - retry_step fix type starts proxy with no rewrite config Made-with: Cursor
Four issues caught by independent reviewers (both flagged #1 and #2): 1. Command parsing: split_whitespace() → sh -c delegation. Handles quoted args, paths with spaces, pipes, and shell variables correctly. 2. Proxy readiness: replaced 500ms sleep with health endpoint polling (20 attempts × 100ms). Surfaces bind errors instead of swallowing them with `let _ =`. Bails with clear message if proxy doesn't start. 3. Session source guard: changed from blocking Direct only to allowlisting Proxy only. Hooks and OtelImport sessions also lack proxy-compatible HTTP blobs and would fail confusingly during replay. 4. Async process: std::process::Command::status() (blocking) → tokio::process::Command::status().await. Prevents blocking the tokio runtime during long-running agent commands. Also: added clap `requires = "apply"` on --command flag so it can't be used without --apply (previously silently ignored). Made-with: Cursor
risjai
left a comment
There was a problem hiding this comment.
Review of rewind fix — AI-powered session diagnosis
Overall this is a well-structured feature with good separation of concerns (Python diagnosis, Rust proxy rewriting, CLI orchestration). The Santa Method review clearly improved quality — the Anthropic provider detection fix and cross-provider guard are solid. Test coverage is good (21 Python + 14 Rust).
6 issues found — 2 bugs, 2 design gaps, 2 nits.
Summary
| # | Severity | Issue |
|---|---|---|
| 1 | 🐛 Bug | run_fix_subprocess blocks the tokio runtime with sync I/O |
| 2 | 🐛 Bug | --step N silently ignores invalid step numbers |
| 3 | proxy_handle.abort() can lose in-flight step data |
|
| 4 | "Scoring" section prints token savings, not LLM eval (diverges from plan) | |
| 5 | 💡 Nit | Manual --apply instructions only show OPENAI_BASE_URL, not ANTHROPIC_BASE_URL |
| 6 | 💡 Nit | Rewrite log fires unconditionally even when no fields actually changed |
See inline comments for details and suggested fixes.
| steps.last().unwrap() | ||
| } | ||
|
|
||
| fn run_fix_subprocess(payload: &serde_json::Value) -> Result<serde_json::Value> { |
There was a problem hiding this comment.
🐛 Bug: Blocking I/O on the tokio runtime.
run_fix_subprocess uses std::process::Command (blocking spawn), std::thread::sleep(50ms) polling loop, and blocking read_to_string. This is called from cmd_fix which is async. It will tie up a tokio worker thread for up to 120s.
The Phase 3 Santa review caught this exact issue for run_agent_command (R2-fix #4: std::process → tokio::process) but the diagnosis subprocess was missed.
Fix: Either:
- Use
tokio::process::Command+tokio::time::timeout(consistent withrun_agent_command), or - Wrap the call in
tokio::task::spawn_blocking(move || run_fix_subprocess(&payload))
The first option is cleaner since the rest of cmd_fix is already async.
| session: &rewind_store::Session, | ||
| step_override: Option<u32>, | ||
| ) -> &'a rewind_store::Step { | ||
| if let Some(n) = step_override { |
There was a problem hiding this comment.
🐛 Bug: --step N silently falls through when N doesn't match any step.
If a user passes --step 999 and no step has that number, this if let quietly falls through to the normal error-step detection cascade. The user thinks they're analyzing step 999 but actually gets the first error step (or last step).
Fix: Return an error when the explicit override doesn't match:
if let Some(n) = step_override {
return steps.iter().find(|s| s.step_number == n)
.context(format!("--step {} not found (session has steps 1..{})", n, steps.last().unwrap().step_number))?;
}Since find_failure_step returns a reference (not Result), you may need to change the signature to Result<&Step> or bail before calling it.
| } | ||
| } | ||
|
|
||
| proxy_handle.abort(); |
There was a problem hiding this comment.
abort() can lose in-flight step data.
proxy_handle.abort() forcefully cancels the proxy task. If the proxy is in the middle of recording a step (writing blobs + inserting into SQLite), that step will be lost or partially written.
Consider sending a shutdown signal instead — the proxy already handles graceful shutdown via Ctrl+C. You could use a tokio::sync::oneshot channel or CancellationToken to signal the proxy to shut down after the agent finishes, then .await the handle with a short timeout before falling back to abort.
Not blocking for v1, but worth a TODO comment at minimum.
| // ── Score both timelines ── | ||
| if !json_output { | ||
| eprintln!(); | ||
| eprintln!("{}", "⏪ Scoring both timelines...".cyan().bold()); |
There was a problem hiding this comment.
The plan (Phase 3.3) says:
"Score both with
llm_judge(criteria:task_completion)" → print "Timeline 'main': task_completion=0.0 ✗ / Timeline 'fix-1': task_completion=1.0 ✓"
But the implementation calls print_session_savings() which prints token/cost savings — no LLM-based eval scoring. The header says "Scoring both timelines..." which is misleading.
Options:
- Wire up actual LLM eval scoring (as spec'd) — probably too much for this PR
- Rename the header to "Replay savings" and drop the pretense of scoring
- Add a TODO with a note that scoring is deferred
Option 2 seems right for v1. The rewind eval score command is already suggested in the follow-up instructions at line 3475, which is good.
| // ── --apply mode: wait for manual re-run ── | ||
| if !json_output { | ||
| println!(" {} Point your agent at this proxy:", "→".cyan()); | ||
| println!(" {}", format!("export OPENAI_BASE_URL=http://127.0.0.1:{}/v1", port).green()); |
There was a problem hiding this comment.
💡 Nit: Missing ANTHROPIC_BASE_URL in manual --apply instructions.
In --command mode (line 3639-3640), both OPENAI_BASE_URL and ANTHROPIC_BASE_URL are set correctly. But here in manual mode, only OPENAI_BASE_URL is printed.
Users with Anthropic-based agents won't know to set the second env var.
println!(" {}", format!("export OPENAI_BASE_URL=http://127.0.0.1:{}/v1", port).green());
println!(" {}", format!("export ANTHROPIC_BASE_URL=http://127.0.0.1:{}/anthropic", port).green());| } | ||
| } | ||
|
|
||
| let final_body = if let Some(ref rewrite) = state.rewrite_config { |
There was a problem hiding this comment.
💡 Nit: Rewrite log fires even when no fields changed.
If rewrite_config is Some(RewriteConfig { model: None, system_inject: None, temperature: None }), this still logs "Applying request rewrite" and clones the body unnecessarily.
The retry_step path in cmd_fix correctly uses new_fork_execute (no rewrite config), so this can't actually happen today. But the log is misleading if someone constructs an empty RewriteConfig in the future.
Consider adding a guard or an is_empty() method on RewriteConfig.
1. Bug: run_fix_subprocess now uses spawn_blocking to avoid blocking the tokio runtime (same issue Santa caught for run_agent_command) 2. Bug: --step N errors when step not found instead of silently falling through to the auto-detection cascade 3. Design: added TODO comment for abort() → graceful shutdown 4. Design: renamed "Scoring both timelines..." to "Replay savings" since we show token/cost savings, not LLM eval scores 5. Nit: added ANTHROPIC_BASE_URL to manual --apply instructions 6. Nit: added RewriteConfig::is_empty() guard so rewrite log only fires when at least one field is set Made-with: Cursor
- Remove unused step_id assignment in test_get_steps_includes_tool_name - Refactor nested if-let to map_err pattern in run_fix_subprocess Made-with: Cursor
Rust workspace + CLI: 0.10.1 → 0.11.0 Python SDK: 0.12.1 → 0.13.0 Covers the rewind fix feature (PR #90): AI-powered diagnosis, proxy request rewriting, hypothesis testing, automated fork-replay. Made-with: Cursor
Rust workspace + CLI: 0.10.1 → 0.11.0 Python SDK: 0.12.1 → 0.13.0 Covers the rewind fix feature (PR #90): AI-powered diagnosis, proxy request rewriting, hypothesis testing, automated fork-replay. Made-with: Cursor
Summary
rewind fix <session>— an LLM-powered command that diagnoses failed agent sessions, suggests fixes, and can automatically fork/replay with proxy-level request patching to verify the fix worksRewriteConfig+apply_rewrites()) that modifies LLM requests after the fork point during replaytool_name+sourcecolumns)Three modes
Fix types
swap_modelinject_systemadjust_temperatureretry_stepno_fixArchitecture
Santa Method review
3 rounds of adversarial review (6 independent reviewers total). Key issues caught and fixed:
Test plan
fix.py(helpers, mocked LLM, subprocess protocol)store.py(tool_name in get_steps/create_step)cargo checkclean, zero warnings