Skip to content

feat: add brainstorm prompt reframing expansion#44

Merged
El-Fitz merged 4 commits into
mainfrom
feat/brainstorm-prompt-reframing-l3
Jun 8, 2026
Merged

feat: add brainstorm prompt reframing expansion#44
El-Fitz merged 4 commits into
mainfrom
feat/brainstorm-prompt-reframing-l3

Conversation

@El-Fitz

@El-Fitz El-Fitz commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Summary

  • add hidden/internal brainstorm --prompt-variants off|per-model
  • generate one strategic prompt reframing per provider, then run all providers across the original anchor plus generated variants
  • preserve benchmark artifact compatibility with flat lineage model IDs and prompt-variant metadata
  • stream-parse Pi JSON events to avoid large stdout buffering failures during L3 runs
  • document L3 smoke results, including updated Kimi-for-coding / MiniMax M3 operability notes

Verification

  • cargo fmt --all -- --check
  • cargo check --workspace
  • cargo test -p refinery_core brainstorm -q
  • cargo test -p refinery_core prompts -q
  • cargo test -p refinery_cli brainstorm -q
  • cargo test --workspace
  • cargo clippy -p refinery_core --all-targets -- -D warnings
  • cargo clippy -p refinery_cli --all-targets -- -D warnings
  • cargo clippy --workspace --all-targets -- -D warnings
  • manual dry-run / benchmark-brainstorm smoke checks
  • Pi-backed L3 smoke runs documented in docs/brainstorms/2026-06-04-brainstorm-l3-prompt-reframing-smoke.md and docs/brainstorms/2026-06-05-brainstorm-l3-updated-model-smoke.md

Notes

Production defaults are unchanged: score-only, prompt-variants off, controversy_floor_7.

@coderabbitai

coderabbitai Bot commented Jun 6, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9f0bbfb9-a066-4b84-9f95-5d1e1ac98784

📥 Commits

Reviewing files that changed from the base of the PR and between 4b06b83 and fc0fa7e.

📒 Files selected for processing (3)
  • crates/refinery_core/src/brainstorm.rs
  • crates/tundish_providers/src/pi.rs
  • crates/tundish_providers/src/process.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/tundish_providers/src/process.rs
  • crates/refinery_core/src/brainstorm.rs
📜 Recent review details
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.rs: Run cargo test --workspace to run all tests
Use cargo build --workspace to build all crates

Files:

  • crates/tundish_providers/src/pi.rs
🔇 Additional comments (2)
crates/tundish_providers/src/pi.rs (2)

254-258: LGTM!


409-417: LGTM!


📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Hidden CLI option to enable per-model prompt-variant expansion for brainstorm benchmarks
    • Benchmark/run outputs now include optional prompt-variant strategy, variant counts, and lineage counts
  • Improvements

    • Dry-run estimates and JSON/text dry-run output now account for prompt-variant expansion
    • Provider handling now parses streaming JSONL incrementally for more robust, memory-efficient responses
  • Documentation

    • Added L3 smoke reports, plans, and rollout notes for prompt-reframing expansion

Walkthrough

This PR adds a hidden per-model prompt-variant expansion mode for brainstorm runs and replaces buffered Pi CLI stdout parsing with a streaming JSONL parser. It updates CLI args/dry-run estimates, persists prompt-variant metadata, rewires propose/evaluate to operate over provider+variant lineages, and adds tests/docs.

Changes

Prompt Variant Expansion with Stream Parsing Fix

Layer / File(s) Summary
Stream-based Pi JSON Parsing
crates/tundish_providers/src/process.rs, crates/tundish_providers/src/pi.rs
Streaming subprocess handling via spawn_cli_stream_lines, bounded stderr/stdout previews, and a stateful PiResponseParser that accumulates text deltas and extracts assistant messages without buffering full output; tests for streaming and bounded error outputs.
Core Brainstorm Variant Expansion Logic
crates/refinery_core/src/brainstorm.rs
Adds BrainstormPromptVariantStrategy and BrainstormPromptVariant, generates per-provider prompt variants with concurrency/timeouts, builds provider+variant lineages, runs propose/evaluate over lineages, adjusts skip/degraded conditions for owner coverage, and persists variants/metadata; includes unit and integration tests.
Prompt Variant Generation Template
crates/refinery_core/src/prompts/brainstorm.rs
Defines BRAINSTORM_PROMPT_VARIANT_SCHEMA and brainstorm_prompt_variant_prompt() to request JSON-only prompt_variant reframings; includes schema and prompt-output tests.
CLI Flag and Dry-Run Integration
crates/refinery_cli/src/commands/brainstorm.rs
Adds hidden --prompt-variants arg, refactors dry-run into emit_dry_run() to compute variant-expanded call counts and lineages, forwards strategy into BrainstormConfig, extends JSON/text outputs with variant fields, and renders variant metadata in text output.
Output Schema and Analyzer Integration
crates/refinery_cli/src/commands/common.rs, converge.rs, synthesize.rs, benchmark_brainstorm.rs
Extends shared DryRunOutput and benchmark analyzer outputs with optional prompt_variant_strategy, prompt_variant_count, and lineage_count; converge/synthesize dry-run payloads add the field as None.
Documentation and Verification
docs/HANDOFF.md, docs/brainstorms/*, docs/plans/*, todos/*
Adds plans, smoke-run logs, and todo updates documenting the prompt-reframing expansion, stream-parse fix, verification results, and rollout guidance.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

A rabbit hops through variants bright,
Reframes each prompt to seek new light,
Streams flow steady, no buffered pain,
Lineages dance across the brain,
Tests and docs confirm the gain. 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding brainstorm prompt reframing expansion as a feature.
Description check ✅ Passed The description is directly related to the changeset, detailing the prompt reframing expansion feature, Pi JSON streaming improvements, and documentation of smoke test results.
Docstring Coverage ✅ Passed Docstring coverage is 90.57% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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/brainstorm-prompt-reframing-l3

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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request implements upstream prompt-variant expansion (L3) for brainstorm runs, introducing a hidden --prompt-variants CLI flag and expanding lineages to run models against strategically reframed prompts. It also refactors the Pi provider to stream-parse JSON event streams incrementally via a new spawn_cli_stream_lines helper, preventing out-of-memory issues from large stdout buffers. The review feedback suggests two valuable improvements: capping the accumulated stderr buffer in the streaming helper to avoid potential OOMs from subprocess stderr, and moving prompt-variant text generation outside of the provider loop to eliminate redundant allocations.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread crates/tundish_providers/src/process.rs Outdated
Comment on lines +360 to +369
let stderr_task = tokio::spawn(async move {
let mut reader = BufReader::new(stderr_handle);
let mut buf = String::new();
while let Ok(n) = reader.read_line(&mut buf).await {
if n == 0 {
break;
}
}
buf
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

To prevent potential out-of-memory (OOM) issues if a subprocess emits an extremely large volume of stderr, the stderr_task should cap the accumulated buffer size while continuing to drain the stream to avoid pipe-buffer deadlocks.

    let stderr_task = tokio::spawn(async move {
        let mut reader = BufReader::new(stderr_handle);
        let mut buf = String::new();
        let mut line = String::new();
        while let Ok(n) = reader.read_line(&mut line).await {
            if n == 0 {
                break;
            }
            if buf.len() < MAX_STREAM_ERROR_OUTPUT_SIZE {
                let remaining = MAX_STREAM_ERROR_OUTPUT_SIZE - buf.len();
                buf.push_str(&line.chars().take(remaining).collect::<String>());
            }
            line.clear();
        }
        buf
    });

Comment on lines +515 to +526
let mut handles = tokio::task::JoinSet::new();
for provider in providers {
let provider = provider.clone();
let model_id = provider.model_id().clone();
let sem = semaphore.clone();
let prompt_text = prompts::brainstorm::brainstorm_prompt_variant_prompt(prompt);
let messages = vec![
Message::system(brainstorm_system_prompt_for_strategy(
BrainstormIterationStrategy::ScoreOnly,
)),
Message::user(prompt_text),
];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

Generating the prompt variant text is independent of the provider and can be done once outside the loop to avoid redundant string formatting and allocations.

Suggested change
let mut handles = tokio::task::JoinSet::new();
for provider in providers {
let provider = provider.clone();
let model_id = provider.model_id().clone();
let sem = semaphore.clone();
let prompt_text = prompts::brainstorm::brainstorm_prompt_variant_prompt(prompt);
let messages = vec![
Message::system(brainstorm_system_prompt_for_strategy(
BrainstormIterationStrategy::ScoreOnly,
)),
Message::user(prompt_text),
];
let mut handles = tokio::task::JoinSet::new();
let prompt_text = prompts::brainstorm::brainstorm_prompt_variant_prompt(prompt);
for provider in providers {
let provider = provider.clone();
let model_id = provider.model_id().clone();
let sem = semaphore.clone();
let messages = vec![
Message::system(brainstorm_system_prompt_for_strategy(
BrainstormIterationStrategy::ScoreOnly,
)),
Message::user(prompt_text.clone()),
];

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4b06b831d2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/tundish_providers/src/pi.rs Outdated
.and_then(|delta| delta.as_str())
{
delta_text.push_str(delta);
self.delta_text.push_str(delta);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid buffering cumulative Pi updates

In Pi streams where message_update events repeat the accumulated assistant content, this still appends every update into delta_text, so the Pi provider can again retain tens of MB (or more) of transport data even when a later message_end supplies the final text. That reintroduces the memory/large-stream failure mode this streaming parser is meant to avoid; store only the latest accumulated update or otherwise avoid accumulating repeated content.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fc0fa7ec35

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if expanded {
ModelId::from_parts(
owner.provider(),
format!("{}+{variant_label}", owner.model()).replace('/', "_"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve distinct slashed model names

When --prompt-variants per-model is used with two models from the same provider whose model names differ only by / versus _ (for example p/a/b and p/a_b, and ModelId explicitly allows slashes in the model portion), this normalization gives both lineages the same ModelId such as p/a_b+original. The proposal and score maps are keyed by that generated ID, so one lineage overwrites the other and the run silently drops/corrupts candidates; use a reversible escaping scheme or keep the real owner ID separate from an artifact-safe filename.

Useful? React with 👍 / 👎.

Comment on lines +256 to +257
} else if !self.delta_text.ends_with(delta) {
self.delta_text.push_str(delta);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Append repeated true delta chunks

If Pi emits true incremental deltas and two adjacent chunks have the same text (for example the answer haha streamed as "ha" then "ha"), this suffix check treats the second chunk as a duplicate and drops it, returning truncated content. The cumulative-update case is already handled by starts_with; for non-cumulative deltas, repeated chunks are valid output and should still be appended.

Useful? React with 👍 / 👎.

@El-Fitz El-Fitz added this pull request to the merge queue Jun 8, 2026
Merged via the queue into main with commit f4606b1 Jun 8, 2026
5 checks passed
@El-Fitz El-Fitz deleted the feat/brainstorm-prompt-reframing-l3 branch June 8, 2026 21:43
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