Skip to content

feat: rewind fix — AI-powered session diagnosis and proxy request rewriting - #90

Merged
risjai merged 9 commits into
masterfrom
feat/rewind-fix-command
Apr 14, 2026
Merged

risjai merged 9 commits into
masterfrom
feat/rewind-fix-command

Conversation

@risjai

@risjai risjai commented Apr 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Adds 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 works
  • Adds proxy request rewriting infrastructure (RewriteConfig + apply_rewrites()) that modifies LLM requests after the fork point during replay
  • Syncs Python store schema with Rust (v0.6 migration: tool_name + source columns)

Three modes

# Diagnosis only — print root cause + suggested fix
rewind fix latest

# Apply the fix — fork, start proxy with rewrites, user re-runs agent
rewind fix latest --apply

# Fully automated — run agent against patched proxy, print savings
rewind fix latest --apply --command "python agent.py"

# Power user — skip diagnosis, directly test a hypothesis
rewind fix latest --apply --hypothesis "swap_model:gpt-4o"

Fix types

Fix type What it does
swap_model Use a different model (same provider only)
inject_system Add a system message (OpenAI + Anthropic string/array)
adjust_temperature Reduce randomness
retry_step Replay same request, exploit LLM non-determinism
no_fix Issue is in agent code, not LLM behavior

Architecture

rewind fix latest --apply --command "python agent.py"
  |
  +-- 1. Load session + steps + blobs from local SQLite
  +-- 2. Spawn python3 -m rewind_agent.fix (diagnosis via LLM function calling)
  +-- 3. Dry-run preview + y/N confirmation (--yes to skip)
  +-- 4. Fork timeline at suggested step
  +-- 5. Start proxy with RewriteConfig (model/system/temperature rewrites)
  +-- 6. Run agent command with OPENAI_BASE_URL pointing at proxy
  +-- 7. Print replay savings (cached tokens, cost, time)

Santa Method review

3 rounds of adversarial review (6 independent reviewers total). Key issues caught and fixed:

  • Anthropic provider detection via model name (not body structure)
  • Cross-provider model swaps blocked with warning
  • Anthropic array-format system field for prompt caching handled
  • Content-Length header filtered after rewrite
  • sys.exit(1) on all Python error paths
  • stdin write errors propagated (not silently swallowed)
  • json.loads of LLM function call arguments wrapped in try/except

Test plan

  • 21 Python tests for fix.py (helpers, mocked LLM, subprocess protocol)
  • 2 Python tests for store.py (tool_name in get_steps/create_step)
  • 14 Rust tests for proxy rewriting (model swap, system inject, temperature, cross-provider, non-JSON)
  • Full Python suite: 267 passed
  • Full Rust suite: 273 passed
  • Anti-pattern grep checks: all clean
  • cargo check clean, zero warnings

risjai added 4 commits April 14, 2026 15:13
…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
@vercel

vercel Bot commented Apr 14, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
rewind Ready Ready Preview, Comment Apr 14, 2026 10:31am

risjai added 3 commits April 14, 2026 15:29
- 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 risjai left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ⚠️ Design proxy_handle.abort() can lose in-flight step data
4 ⚠️ Design "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.

Comment thread crates/rewind-cli/src/main.rs Outdated
steps.last().unwrap()
}

fn run_fix_subprocess(payload: &serde_json::Value) -> Result<serde_json::Value> {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🐛 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 with run_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 {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🐛 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();

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Design: 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.

Comment thread crates/rewind-cli/src/main.rs Outdated
// ── Score both timelines ──
if !json_output {
eprintln!();
eprintln!("{}", "⏪ Scoring both timelines...".cyan().bold());

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Design: "Scoring" diverges from the plan spec.

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:

  1. Wire up actual LLM eval scoring (as spec'd) — probably too much for this PR
  2. Rename the header to "Replay savings" and drop the pretense of scoring
  3. 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());

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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());

Comment thread crates/rewind-proxy/src/lib.rs Outdated
}
}

let final_body = if let Some(ref rewrite) = state.rewrite_config {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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.

risjai added 2 commits April 14, 2026 15:58
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
@risjai
risjai enabled auto-merge (squash) April 14, 2026 10:32
@risjai
risjai merged commit 2ea4e98 into master Apr 14, 2026
6 checks passed
@risjai
risjai deleted the feat/rewind-fix-command branch April 14, 2026 10:33
risjai added a commit that referenced this pull request Apr 14, 2026
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
risjai added a commit that referenced this pull request Apr 14, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant