Skip to content

git: add bounded rewrite scenario orchestration#5

Merged
bschellenberger2600 merged 3 commits intomainfrom
feat/gmt-watch-rewrite-scenarios
Apr 16, 2026
Merged

git: add bounded rewrite scenario orchestration#5
bschellenberger2600 merged 3 commits intomainfrom
feat/gmt-watch-rewrite-scenarios

Conversation

@bschellenberger2600
Copy link
Copy Markdown
Member

@bschellenberger2600 bschellenberger2600 commented Apr 16, 2026

Summary

  • add RunRewriteScenario to orchestrate bounded detect/intervene/verify rewrite passes
  • expose pass-by-pass telemetry and explicit max-attempt error semantics
  • document local commands for validating rewrite-orchestration behavior

Test plan

  • go test -count=1 ./git -run RunRewriteScenario
  • go test -count=1 ./...

Made with Cursor


Note

Low Risk
Additive, isolated orchestration helper with extensive unit coverage and no changes to existing behavior.

Overview
Adds a new git.RunRewriteScenario API that runs a bounded detect → intervene → verify loop, returns pass-by-pass telemetry (RewriteScenarioResult.Passes), and fails with ErrRewriteAttemptsExceeded when the repo never becomes clean within MaxAttempts.

Includes a comprehensive test suite covering clean short-circuiting, multi-pass behavior, callback failures, context cancellation at multiple phases, and option validation, plus README documentation and local test commands for validating the orchestration flow.

Reviewed by Cursor Bugbot for commit 4e4e936. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features

    • Added multi-pass rewrite orchestration workflow that automatically detects issues, applies interventions, and verifies cleanliness in loop cycles until resolved or max attempts exhausted.
    • New error handling for exceeded attempt limits with detailed pass history tracking.
  • Documentation

    • Added documentation describing the rewrite orchestration flow, control patterns, and validation procedures.

Introduce detect/intervene/verify rerun orchestration with max-attempt guards so rewrite pipelines can fail predictably and report pass-by-pass state.

Made-with: Cursor
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 16, 2026

📝 Walkthrough

Walkthrough

This PR introduces a rewrite orchestration utility in the git package. It adds RunRewriteScenario function with supporting types and an error definition to manage multi-pass rewrite workflows through detection, intervention, and verification callbacks. Comprehensive tests and documentation accompany the feature.

Changes

Cohort / File(s) Summary
Core Orchestration
git/rewrite_scenario.go
New module defining orchestration logic for bounded multi-pass rewrite workflows. Introduces RunRewriteScenario function, supporting types (RewriteScenarioOptions, RewriteScenarioResult, RewriteAttempt), and ErrRewriteAttemptsExceeded. Handles callback invocation with context cancellation checks and contextual error wrapping.
Test Suite
git/rewrite_scenario_test.go
Comprehensive unit tests validating orchestration control flow, callback invocation sequencing, result structure accuracy, error handling for exceeded attempts and callback failures, and configuration validation.
Documentation
README.md
New section documenting "Rewrite Orchestration (git-fcuk flow)" with bounded multi-pass workflow description, control flow diagram (detect → intervene → verify), telemetry details, validation commands, and success criteria.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hopping through rewrites with paws so quick,
A scenario runs where callbacks do trick—
Detect, intervene, verify, and pass,
Till clean repositories shine like glass!
Multi-pass magic, orchestrated with care,
The git-fcuk flow floats through the air! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'git: add bounded rewrite scenario orchestration' accurately summarizes the main change—introduction of the RunRewriteScenario function and related types for orchestrating bounded rewrite workflows.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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 feat/gmt-watch-rewrite-scenarios

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.

@bschellenberger2600
Copy link
Copy Markdown
Member Author

bugbot-review

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
git/rewrite_scenario_test.go (1)

250-279: Add explicit tests for cancellation and nil-context fallback.

Given cancellation is part of runtime control flow, add targeted tests for a canceled context and for ctx == nil to lock down these contracts.

🧪 Suggested test additions
+func TestRunRewriteScenario_CancelledContext(t *testing.T) {
+	ctx, cancel := context.WithCancel(context.Background())
+	cancel()
+
+	result, err := RunRewriteScenario(ctx, RewriteScenarioOptions{
+		MaxAttempts: 2,
+		Detect: func(_ context.Context, _ int) (bool, error) { return true, nil },
+		Intervene: func(_ context.Context, _ int) error { return nil },
+		Verify: func(_ context.Context, _ int) (bool, error) { return false, nil },
+	})
+	if err == nil {
+		t.Fatal("RunRewriteScenario() error = nil, want cancellation error")
+	}
+	if result.Attempts != 0 {
+		t.Fatalf("result.Attempts = %d, want 0", result.Attempts)
+	}
+}
+
+func TestRunRewriteScenario_NilContextFallback(t *testing.T) {
+	result, err := RunRewriteScenario(nil, RewriteScenarioOptions{
+		MaxAttempts: 1,
+		Detect: func(_ context.Context, _ int) (bool, error) { return false, nil },
+		Intervene: func(_ context.Context, _ int) error { return nil },
+		Verify: func(_ context.Context, _ int) (bool, error) { return true, nil },
+	})
+	if err != nil {
+		t.Fatalf("RunRewriteScenario() error = %v", err)
+	}
+	if !result.Clean {
+		t.Fatalf("result.Clean = false, want true")
+	}
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@git/rewrite_scenario_test.go` around lines 250 - 279, Add two explicit unit
tests to TestRunRewriteScenario (or new tests) to cover cancellation and
nil-context fallback: call RunRewriteScenario with a context canceled before
invocation (use context.WithCancel and cancel()) and assert it returns a
context/cancellation-related error; also call RunRewriteScenario passing nil as
the ctx and assert it behaves the same as context.Background() (i.e., does not
panic and honors callbacks), using the same RewriteScenarioOptions callbacks
(Detect, Intervene, Verify) as in existing tests to verify expected handling.
Ensure you reference RunRewriteScenario and RewriteScenarioOptions and keep
assertions specific to cancellation and nil-context behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@git/rewrite_scenario.go`:
- Around line 72-107: The loop currently only checks ctx.Err() at the start of
each attempt; add cancellation checks immediately after each callback phase
(after calling opts.Detect and after opts.Intervene, and optionally after
opts.Verify if you want mid-verify cancellation) so we don't proceed to
subsequent callbacks when ctx is cancelled. On detecting cancellation populate
result.Attempts and result.Passes consistently (e.g., set result.Attempts =
attempt, append the current RewriteAttempt pass), and return a wrapped error
like fmt.Errorf("rewrite scenario cancelled before <phase> on attempt %d: %w",
attempt, ctx.Err()) to preserve the original context error; update the logic
around RewriteAttempt, opts.Detect, opts.Intervene, and opts.Verify to perform
these checks and early returns.

---

Nitpick comments:
In `@git/rewrite_scenario_test.go`:
- Around line 250-279: Add two explicit unit tests to TestRunRewriteScenario (or
new tests) to cover cancellation and nil-context fallback: call
RunRewriteScenario with a context canceled before invocation (use
context.WithCancel and cancel()) and assert it returns a
context/cancellation-related error; also call RunRewriteScenario passing nil as
the ctx and assert it behaves the same as context.Background() (i.e., does not
panic and honors callbacks), using the same RewriteScenarioOptions callbacks
(Detect, Intervene, Verify) as in existing tests to verify expected handling.
Ensure you reference RunRewriteScenario and RewriteScenarioOptions and keep
assertions specific to cancellation and nil-context behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: adf60cd2-c371-4eca-9352-8e4b84787b83

📥 Commits

Reviewing files that changed from the base of the PR and between 377c314 and 921cf3f.

📒 Files selected for processing (3)
  • README.md
  • git/rewrite_scenario.go
  • git/rewrite_scenario_test.go

Comment thread git/rewrite_scenario.go
@bschellenberger2600
Copy link
Copy Markdown
Member Author

@cursoragent address feedback then kick off a bugbot review after

@cursor
Copy link
Copy Markdown

cursor bot commented Apr 16, 2026

Here is what was done.

Code changes

  • RunRewriteScenario now checks ctx.Err() after Detect when intervention is still needed (before Intervene) and again after Intervene (before Verify). On cancellation it sets result.Attempts to the current attempt, appends the in-progress RewriteAttempt, and returns a wrapped error (cancelled before intervene / cancelled before verify) so errors.Is(..., context.Canceled) still works.

Tests

  • TestRunRewriteScenario_CancelledContext — context already canceled before the loop; expects context.Canceled and Attempts == 0.
  • TestRunRewriteScenario_NilContextFallbacknil context does not panic and Detect runs (same shape as other tests).
  • TestRunRewriteScenario_CancelledAfterDetectSkipsIntervene / TestRunRewriteScenario_CancelledAfterInterveneSkipsVerify — cancel from inside the prior callback; later phases must not run.

Git / PR

Bugbot review

  • Posting gh pr comment 5 --body "bugbot-review" failed with Resource not accessible by integration (this environment’s token cannot add PR comments). Please add a comment bugbot-review on PR #5 from an account that can comment, or trigger Bugbot from the GitHub UI if that’s how your org does it.

Tests run: go test -count=1 ./git -run RunRewriteScenario and go test -count=1 ./... (both passed).

Open in Web Open in Cursor 

Check ctx.Err after detect (when intervention needed) and after
intervene so later callbacks are skipped when cancelled. Add tests
for pre-cancelled context, nil context fallback, and mid-attempt
cancellation before intervene and verify.

Co-authored-by: Ben Schellenberger <bschellenberger2600@users.noreply.github.com>
@bschellenberger2600
Copy link
Copy Markdown
Member Author

@cursoragent review

@cursor
Copy link
Copy Markdown

cursor bot commented Apr 16, 2026

Review outcome

CodeRabbit’s “cancellation between phases” point is already satisfied on main’s PR line in commit e8f8fef: ctx.Err() is checked after Detect (when intervention is needed) and after Intervene, with Attempts / Passes updated and wrapped errors that still allow errors.Is(..., context.Canceled).

One gap I fixed: on the last attempt, if Verify returns clean == false and the context is cancelled inside Verify, the loop would end without another ctx.Err() at the top of a new attempt, so the function could return ErrRewriteAttemptsExceeded instead of a cancellation error. That misclassifies “we ran out of attempts because we were cancelled mid-verify” as “repo stayed dirty.”

Change (now on the branch): after a non-clean verify, check ctx.Err() and return a wrapped cancellation error (cancelled after verify on attempt %d) with Attempts set and the pass already appended. TestRunRewriteScenario_CancelledInVerifyOnLastAttempt locks this in.

Pushed as 4e4e936 and PR #5 was refreshed (base_branch: main). Tests: go test -count=1 ./git -run RunRewriteScenario and go test -count=1 ./git passed.

Optional follow-ups (not changed): CodeRabbit’s docstring coverage warning is tooling noise unless you want docstrings on every exported symbol; Bugbot already ran on e8f8fef per the PR summary—comment bugbot-review again on the PR if you want a pass on the new commit.

Open in Web Open in Cursor 

When verify reports not clean on the last attempt and the context is
cancelled during verify, return a cancellation error instead of
ErrRewriteAttemptsExceeded. Add a regression test.

Co-authored-by: Ben Schellenberger <bschellenberger2600@users.noreply.github.com>
@bschellenberger2600 bschellenberger2600 merged commit a342dfc into main Apr 16, 2026
3 checks passed
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.

2 participants