diff --git a/checkpoint.json b/checkpoint.json index 28622bbed..778ff418e 100644 --- a/checkpoint.json +++ b/checkpoint.json @@ -1,6 +1,6 @@ { - "timestamp": "2026-03-16T04:50:45.015292Z", - "current_node": "simplify_gemini", + "timestamp": "2026-03-16T05:01:09.792908Z", + "current_node": "simplify_gpt", "completed_nodes": [ "start", "toolchain", @@ -8,24 +8,27 @@ "preflight_lint", "implement", "simplify_opus", - "simplify_gemini" + "simplify_gemini", + "simplify_gpt" ], "node_retries": { + "implement": 1, + "simplify_gpt": 1, + "toolchain": 1, "preflight_lint": 1, "preflight_compile": 1, "start": 1, - "implement": 1, "simplify_opus": 1, - "simplify_gemini": 1, - "toolchain": 1 + "simplify_gemini": 1 }, "context_values": { "internal.retry_count.simplify_gemini": 1, "internal.node_visit_count": 1, - "last_response": "Everything passes. Here's a summary of what was fixed:\n\n## Summary\n\n### Fixed Issues\n\n1. **Stringly-typed provider comparison** (`cli/run.rs`): Replaced `provider_name == \"docker\"` and `provider_name ", + "last_response": "All clean. Here's a summary of what was fixed:\n\n## Summary of Changes\n\n### Fixed Issues\n\n1. **Eliminated `FinalizeConfig` struct (−52 lines)** — Changed `run_with_lifecycle` to take `config: &mut ", "graph.model_stylesheet": "\n * { backend: api; model: claude-opus-4-6;}\n ", "outcome": "success", "command.output": "", + "internal.retry_count.simplify_gpt": 1, "internal.retry_count.start": 1, "thread.simplify_opus.current_node": "simplify_gemini", "failure_signature": "", @@ -40,8 +43,10 @@ "graph.rankdir": "LR", "internal.retry_count.preflight_compile": 1, "internal.retry_count.simplify_opus": 1, - "current.preamble": "Goal: # Plan: Move sandbox lifecycle into the engine\n\n## Context\n\n`SandboxReady` and `SandboxCleanup` hook events are defined in `HookEvent` but never fired. They can't fire naturally because sandbox init/cleanup happens in `cli/run.rs` — outside the engine where all other hooks fire. The root cause is that `cli/run.rs` is a ~2000-line god function orchestrating everything: sandbox creation, init, setup commands, devcontainer lifecycle, engine construction, engine run, retro, PR creation, and cleanup. The engine receives an already-initialized sandbox and has no role in lifecycle management.\n\nThis refactor moves sandbox initialization and setup into the engine so `SandboxReady` fires naturally alongside `RunStart`. Cleanup stays callable from the CLI (the retro agent needs the sandbox alive after the graph completes) but fires through an engine method so `SandboxCleanup` also uses the hook infrastructure.\n\n## Design\n\n### Two new engine methods\n\n**`run_with_lifecycle(graph, config, lifecycle, checkpoint?) -> Result`**\n1. `sandbox.initialize()`\n2. Fire `SandboxReady` hook (blocking — can abort run)\n3. Emit `SandboxInitialized` event (CLI listener writes `sandbox.json`, updates progress UI)\n4. Remote git setup if `sandbox.is_remote()` — produces `base_sha`, `run_branch`, `base_branch`, merged into `config`\n5. Run setup commands inside sandbox\n6. Run devcontainer lifecycle phases inside sandbox\n7. Call existing `run_internal()` (unchanged — fires RunStart → graph → RunComplete)\n8. Return outcome (sandbox still alive)\n\n**`cleanup_sandbox(run_id, workflow_name, preserve) -> Result<()>`**\n1. Fire `SandboxCleanup` hook (non-blocking)\n2. If `!preserve`: call `sandbox.cleanup()`\n\nExisting `run()` is unchanged — API server and integration tests keep using it with pre-initialized sandboxes.\n\n### New config struct\n\n```rust\n// engine.rs\npub struct LifecycleConfig {\n pub setup_commands: Vec,\n pub setup_command_timeout_ms: u64,\n pub devcontainer_phases: Vec<(String, Vec)>,\n}\n```\n\n`run_with_lifecycle` takes `config: RunConfig` by value (currently `&RunConfig`) so it can fill in remote git values. `run_internal` continues to take `&RunConfig`.\n\n### CLI flow after refactor\n\n```\nsandbox = create_sandbox() // unchanged\nsandbox = ReadBeforeWriteSandbox::new(sandbox) // moved before init (delegate_sandbox! delegates initialize)\nengine = build_engine(sandbox, hook_runner, ...)\noutcome = engine.run_with_lifecycle(graph, config, lifecycle)\n// retro, conclusion, PR creation — sandbox still alive\nengine.cleanup_sandbox(run_id, workflow_name, preserve)\n```\n\nSingle scopeguard around the entire block that calls `engine.cleanup_sandbox()` on panic.\n\n## Steps\n\n### 1. `hook/types.rs` — Make `SandboxReady` blocking by default\n- Add `Self::SandboxReady` to `is_blocking_by_default()` match arm (line 29-32)\n- `SandboxCleanup` stays non-blocking (correct default)\n\n### 2. `engine.rs` — Add `LifecycleConfig` struct and `run_with_lifecycle` method\n- Define `LifecycleConfig` (setup_commands, setup_command_timeout_ms, devcontainer_phases)\n- Add `pub async fn run_with_lifecycle(self, graph, config, lifecycle, checkpoint) -> Result` that:\n - Calls `self.services.sandbox.initialize()`\n - Fires `SandboxReady` hook via `self.run_hooks()`\n - Emits `WorkflowRunEvent::SandboxInitialized { working_directory }` via emitter\n - Calls remote git setup if `sandbox.is_remote()`, fills config.base_sha/run_branch/base_branch/git_checkpoint_enabled\n - Runs setup commands via `sandbox.exec_command()`, emitting Setup* events\n - Runs devcontainer lifecycle via `devcontainer_bridge::run_devcontainer_lifecycle()`\n - Calls `self.run_internal()` (or `run_from_checkpoint` path)\n - Returns outcome\n\n### 3. `engine.rs` — Add `cleanup_sandbox` method\n- `pub async fn cleanup_sandbox(&self, run_id, workflow_name, preserve) -> Result<(), String>`\n- Fires `SandboxCleanup` hook\n- If `!preserve`: calls `self.services.sandbox.cleanup()`\n\n### 4. `engine.rs` — Move `setup_remote_git` from `cli/run.rs`\n- Move the `setup_remote_git()` function (cli/run.rs line 1636-1679) into engine.rs\n- It only uses `sandbox.exec_command()` and `run_id` — no CLI dependencies\n\n### 5. `event.rs` — Add `SandboxInitialized` event variant\n- Add `WorkflowRunEvent::SandboxInitialized { working_directory: String }` variant\n- This replaces the inline sandbox.json writing in cli/run.rs\n\n### 6. `cli/run.rs` — Register event listener for sandbox.json\n- Before calling `run_with_lifecycle`, register a listener on the emitter for `SandboxInitialized`\n- Listener captures the pre-built `SandboxRecord` template (all provider-specific fields filled, `working_directory` empty)\n- On event: fill `working_directory` from event, call `record.save()`\n- Also update progress UI `set_working_directory` in the same listener\n\n### 7. `cli/run.rs` — Refactor `run_command` to use new engine methods\n- Move `ReadBeforeWriteSandbox` wrapping to before engine construction (currently at line 966, after init — delegate_sandbox! macro delegates initialize so wrapping before init works)\n- Move `HookRunner` creation earlier (before engine construction) — currently line 1222, move to ~line 800\n- Remove: `sandbox.initialize()` (line 886), remote git setup (lines 982-996), setup commands (lines 1031-1072), devcontainer lifecycle (lines 1074-1091)\n- Build `LifecycleConfig` from `setup_commands` and `devcontainer_config`\n- Build `RunConfig` without remote git fields (leave base_sha/run_branch/base_branch as None for remote — engine fills them)\n- Call `engine.run_with_lifecycle()` instead of `engine.run()`\n- Replace cleanup section (lines 1587-1604) with `engine.cleanup_sandbox()`\n- Replace two scopeguards with one that calls `engine.cleanup_sandbox()` on panic\n- Remove `status_guard` for SandboxInitFailed — engine handles init errors\n\n### 8. `cli/run.rs` — Refactor `run_from_branch` to use new engine methods\n- Use `run_with_lifecycle` with empty `LifecycleConfig` (no setup commands, no devcontainer)\n- Add `cleanup_sandbox()` call (currently no scopeguard — this is an improvement)\n- This gives the resume path hooks for free (currently has zero hooks)\n\n### 9. `docs/agents/hooks.mdx` — Update docs\n- Remove any \"reserved\" annotations for `sandbox_ready` / `sandbox_cleanup`\n- Note that `sandbox_ready` is blocking by default\n\n## Files to modify\n- `lib/crates/fabro-workflows/src/hook/types.rs` — SandboxReady blocking default\n- `lib/crates/fabro-workflows/src/engine.rs` — LifecycleConfig, run_with_lifecycle, cleanup_sandbox, setup_remote_git\n- `lib/crates/fabro-workflows/src/event.rs` — SandboxInitialized event variant\n- `lib/crates/fabro-workflows/src/cli/run.rs` — major simplification of run_command and run_from_branch\n- `docs/agents/hooks.mdx` — remove \"reserved\" annotations\n\n## Files unchanged\n- `lib/crates/fabro-workflows/src/handler/mod.rs` — EngineServices unchanged\n- `lib/crates/fabro-workflows/src/hook/runner.rs` — handles any HookEvent generically\n- `lib/crates/fabro-agent/src/sandbox.rs` — Sandbox trait unchanged\n- `lib/crates/fabro-agent/src/read_before_write_sandbox.rs` — delegate_sandbox! already delegates initialize/cleanup\n- All sandbox implementations — unchanged\n\n## Verification\n1. `cargo build --workspace` — compile check\n2. `cargo test --workspace` — all existing tests pass (existing `run()` path unchanged)\n3. `cargo clippy --workspace -- -D warnings` — no new warnings\n4. Manual test: `fabro run` with a workflow that has `sandbox_ready` and `sandbox_cleanup` hooks configured — verify hooks fire\n5. Manual test: `fabro run --sandbox daytona` — verify remote git setup still works through the engine\n6. Manual test: `fabro run` with `--preserve-sandbox` — verify cleanup is skipped but SandboxCleanup hook still fires\n\n\n## Completed stages\n- **toolchain**: success\n - Script: `command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1`\n - Stdout:\n ```\n cargo 1.94.0 (85eff7c80 2026-01-15)\n ```\n - Stderr: (empty)\n- **preflight_compile**: success\n - Script: `cargo check -q --workspace 2>&1`\n - Stdout: (empty)\n - Stderr: (empty)\n- **preflight_lint**: success\n - Script: `cargo clippy -q --workspace -- -D warnings 2>&1`\n - Stdout: (empty)\n - Stderr: (empty)\n- **implement**: success\n - Model: claude-opus-4-6, 172.3k tokens in / 48.5k out\n - Files: /home/daytona/workspace/docs/agents/hooks.mdx, /home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/event.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/hook/types.rs\n- **simplify_opus**: success\n - Model: claude-opus-4-6, 90.5k tokens in / 16.9k out\n - Files: /home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs\n", - "current_node": "simplify_gemini", + "response.simplify_gpt": "All clean. Here's a summary of what was fixed:\n\n## Summary of Changes\n\n### Fixed Issues\n\n1. **Eliminated `FinalizeConfig` struct (−52 lines)** — Changed `run_with_lifecycle` to take `config: &mut RunConfig` instead of consuming `config: RunConfig` by value. This means:\n - The caller retains ownership of `RunConfig` and can read any fields mutated by remote git setup (e.g., `run_branch`, `base_sha`) directly after the call\n - Deleted the entire `FinalizeConfig` struct, its `from_run_config()` and `from_run_config_owned()` constructors\n - Renamed `write_finalize_commit_from(&FinalizeConfig)` back to `write_finalize_commit(&RunConfig)`\n - Simplified all `match &engine_result { Ok((ref o, _)) => ... }` to `match &engine_result { Ok(ref o) => ... }`\n - Eliminated all `finalize_config.field` references, using `config.field` directly\n - The error path is now actually more correct: if remote git setup succeeded but a later step failed, the caller still sees the populated metadata branch fields (previously they were reset to `None` in `from_run_config_owned`)\n\n2. **Eliminated duplicated `run_internal` calls in `run_with_lifecycle` (−12 lines)** — Step 7 was manually calling `run_internal` with identical logic to the existing `run()` and `run_from_checkpoint()` methods. Now it simply delegates to those existing public methods.\n\n3. **Fixed misleading `_ssh_command` variable name** — The variable is used in the `tracing::info!` macro, so the leading underscore was incorrect. Changed to `ssh_command`.\n\n**Net impact: −83 lines** (44 insertions, 127 deletions across the cleanup diff)", + "thread.simplify_gemini.current_node": "simplify_gpt", + "current.preamble": "Goal: # Plan: Move sandbox lifecycle into the engine\n\n## Context\n\n`SandboxReady` and `SandboxCleanup` hook events are defined in `HookEvent` but never fired. They can't fire naturally because sandbox init/cleanup happens in `cli/run.rs` — outside the engine where all other hooks fire. The root cause is that `cli/run.rs` is a ~2000-line god function orchestrating everything: sandbox creation, init, setup commands, devcontainer lifecycle, engine construction, engine run, retro, PR creation, and cleanup. The engine receives an already-initialized sandbox and has no role in lifecycle management.\n\nThis refactor moves sandbox initialization and setup into the engine so `SandboxReady` fires naturally alongside `RunStart`. Cleanup stays callable from the CLI (the retro agent needs the sandbox alive after the graph completes) but fires through an engine method so `SandboxCleanup` also uses the hook infrastructure.\n\n## Design\n\n### Two new engine methods\n\n**`run_with_lifecycle(graph, config, lifecycle, checkpoint?) -> Result`**\n1. `sandbox.initialize()`\n2. Fire `SandboxReady` hook (blocking — can abort run)\n3. Emit `SandboxInitialized` event (CLI listener writes `sandbox.json`, updates progress UI)\n4. Remote git setup if `sandbox.is_remote()` — produces `base_sha`, `run_branch`, `base_branch`, merged into `config`\n5. Run setup commands inside sandbox\n6. Run devcontainer lifecycle phases inside sandbox\n7. Call existing `run_internal()` (unchanged — fires RunStart → graph → RunComplete)\n8. Return outcome (sandbox still alive)\n\n**`cleanup_sandbox(run_id, workflow_name, preserve) -> Result<()>`**\n1. Fire `SandboxCleanup` hook (non-blocking)\n2. If `!preserve`: call `sandbox.cleanup()`\n\nExisting `run()` is unchanged — API server and integration tests keep using it with pre-initialized sandboxes.\n\n### New config struct\n\n```rust\n// engine.rs\npub struct LifecycleConfig {\n pub setup_commands: Vec,\n pub setup_command_timeout_ms: u64,\n pub devcontainer_phases: Vec<(String, Vec)>,\n}\n```\n\n`run_with_lifecycle` takes `config: RunConfig` by value (currently `&RunConfig`) so it can fill in remote git values. `run_internal` continues to take `&RunConfig`.\n\n### CLI flow after refactor\n\n```\nsandbox = create_sandbox() // unchanged\nsandbox = ReadBeforeWriteSandbox::new(sandbox) // moved before init (delegate_sandbox! delegates initialize)\nengine = build_engine(sandbox, hook_runner, ...)\noutcome = engine.run_with_lifecycle(graph, config, lifecycle)\n// retro, conclusion, PR creation — sandbox still alive\nengine.cleanup_sandbox(run_id, workflow_name, preserve)\n```\n\nSingle scopeguard around the entire block that calls `engine.cleanup_sandbox()` on panic.\n\n## Steps\n\n### 1. `hook/types.rs` — Make `SandboxReady` blocking by default\n- Add `Self::SandboxReady` to `is_blocking_by_default()` match arm (line 29-32)\n- `SandboxCleanup` stays non-blocking (correct default)\n\n### 2. `engine.rs` — Add `LifecycleConfig` struct and `run_with_lifecycle` method\n- Define `LifecycleConfig` (setup_commands, setup_command_timeout_ms, devcontainer_phases)\n- Add `pub async fn run_with_lifecycle(self, graph, config, lifecycle, checkpoint) -> Result` that:\n - Calls `self.services.sandbox.initialize()`\n - Fires `SandboxReady` hook via `self.run_hooks()`\n - Emits `WorkflowRunEvent::SandboxInitialized { working_directory }` via emitter\n - Calls remote git setup if `sandbox.is_remote()`, fills config.base_sha/run_branch/base_branch/git_checkpoint_enabled\n - Runs setup commands via `sandbox.exec_command()`, emitting Setup* events\n - Runs devcontainer lifecycle via `devcontainer_bridge::run_devcontainer_lifecycle()`\n - Calls `self.run_internal()` (or `run_from_checkpoint` path)\n - Returns outcome\n\n### 3. `engine.rs` — Add `cleanup_sandbox` method\n- `pub async fn cleanup_sandbox(&self, run_id, workflow_name, preserve) -> Result<(), String>`\n- Fires `SandboxCleanup` hook\n- If `!preserve`: calls `self.services.sandbox.cleanup()`\n\n### 4. `engine.rs` — Move `setup_remote_git` from `cli/run.rs`\n- Move the `setup_remote_git()` function (cli/run.rs line 1636-1679) into engine.rs\n- It only uses `sandbox.exec_command()` and `run_id` — no CLI dependencies\n\n### 5. `event.rs` — Add `SandboxInitialized` event variant\n- Add `WorkflowRunEvent::SandboxInitialized { working_directory: String }` variant\n- This replaces the inline sandbox.json writing in cli/run.rs\n\n### 6. `cli/run.rs` — Register event listener for sandbox.json\n- Before calling `run_with_lifecycle`, register a listener on the emitter for `SandboxInitialized`\n- Listener captures the pre-built `SandboxRecord` template (all provider-specific fields filled, `working_directory` empty)\n- On event: fill `working_directory` from event, call `record.save()`\n- Also update progress UI `set_working_directory` in the same listener\n\n### 7. `cli/run.rs` — Refactor `run_command` to use new engine methods\n- Move `ReadBeforeWriteSandbox` wrapping to before engine construction (currently at line 966, after init — delegate_sandbox! macro delegates initialize so wrapping before init works)\n- Move `HookRunner` creation earlier (before engine construction) — currently line 1222, move to ~line 800\n- Remove: `sandbox.initialize()` (line 886), remote git setup (lines 982-996), setup commands (lines 1031-1072), devcontainer lifecycle (lines 1074-1091)\n- Build `LifecycleConfig` from `setup_commands` and `devcontainer_config`\n- Build `RunConfig` without remote git fields (leave base_sha/run_branch/base_branch as None for remote — engine fills them)\n- Call `engine.run_with_lifecycle()` instead of `engine.run()`\n- Replace cleanup section (lines 1587-1604) with `engine.cleanup_sandbox()`\n- Replace two scopeguards with one that calls `engine.cleanup_sandbox()` on panic\n- Remove `status_guard` for SandboxInitFailed — engine handles init errors\n\n### 8. `cli/run.rs` — Refactor `run_from_branch` to use new engine methods\n- Use `run_with_lifecycle` with empty `LifecycleConfig` (no setup commands, no devcontainer)\n- Add `cleanup_sandbox()` call (currently no scopeguard — this is an improvement)\n- This gives the resume path hooks for free (currently has zero hooks)\n\n### 9. `docs/agents/hooks.mdx` — Update docs\n- Remove any \"reserved\" annotations for `sandbox_ready` / `sandbox_cleanup`\n- Note that `sandbox_ready` is blocking by default\n\n## Files to modify\n- `lib/crates/fabro-workflows/src/hook/types.rs` — SandboxReady blocking default\n- `lib/crates/fabro-workflows/src/engine.rs` — LifecycleConfig, run_with_lifecycle, cleanup_sandbox, setup_remote_git\n- `lib/crates/fabro-workflows/src/event.rs` — SandboxInitialized event variant\n- `lib/crates/fabro-workflows/src/cli/run.rs` — major simplification of run_command and run_from_branch\n- `docs/agents/hooks.mdx` — remove \"reserved\" annotations\n\n## Files unchanged\n- `lib/crates/fabro-workflows/src/handler/mod.rs` — EngineServices unchanged\n- `lib/crates/fabro-workflows/src/hook/runner.rs` — handles any HookEvent generically\n- `lib/crates/fabro-agent/src/sandbox.rs` — Sandbox trait unchanged\n- `lib/crates/fabro-agent/src/read_before_write_sandbox.rs` — delegate_sandbox! already delegates initialize/cleanup\n- All sandbox implementations — unchanged\n\n## Verification\n1. `cargo build --workspace` — compile check\n2. `cargo test --workspace` — all existing tests pass (existing `run()` path unchanged)\n3. `cargo clippy --workspace -- -D warnings` — no new warnings\n4. Manual test: `fabro run` with a workflow that has `sandbox_ready` and `sandbox_cleanup` hooks configured — verify hooks fire\n5. Manual test: `fabro run --sandbox daytona` — verify remote git setup still works through the engine\n6. Manual test: `fabro run` with `--preserve-sandbox` — verify cleanup is skipped but SandboxCleanup hook still fires\n\n\n## Completed stages\n- **toolchain**: success\n - Script: `command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1`\n - Stdout:\n ```\n cargo 1.94.0 (85eff7c80 2026-01-15)\n ```\n - Stderr: (empty)\n- **preflight_compile**: success\n - Script: `cargo check -q --workspace 2>&1`\n - Stdout: (empty)\n - Stderr: (empty)\n- **preflight_lint**: success\n - Script: `cargo clippy -q --workspace -- -D warnings 2>&1`\n - Stdout: (empty)\n - Stderr: (empty)\n- **implement**: success\n - Model: claude-opus-4-6, 172.3k tokens in / 48.5k out\n - Files: /home/daytona/workspace/docs/agents/hooks.mdx, /home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/event.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/hook/types.rs\n- **simplify_opus**: success\n - Model: claude-opus-4-6, 90.5k tokens in / 16.9k out\n - Files: /home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs\n- **simplify_gemini**: success\n - Model: claude-opus-4-6, 92.0k tokens in / 18.0k out\n - Files: /home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs\n", + "current_node": "simplify_gpt", "thread.toolchain.current_node": "preflight_compile", "thread.preflight_lint.current_node": "implement", "response.implement": "All 1655 unit tests pass. 179 integration tests pass. No failures.\n\nLet me do one final summary of all the changes made:\n\n## Summary of Changes\n\n### 1. `lib/crates/fabro-workflows/src/hook/types.rs`\n- Added `Self::SandboxReady` to `is_blocking_by_default()` match arm — `SandboxReady` is now blocking by default\n- Updated test `hook_event_blocking_defaults` to verify `SandboxReady` is blocking and `SandboxCleanup` is not\n\n### 2. `lib/crates/fabro-workflows/src/event.rs`\n- Added `WorkflowRunEvent::SandboxInitialized { working_directory: String }` variant\n- Added `trace()` implementation for the new variant (logs via `info!`)\n- Added serialization/deserialization test\n- Added `flatten_event` test\n\n### 3. `lib/crates/fabro-workflows/src/engine.rs`\n- Added `setup_remote_git()` public function (moved from `cli/run.rs`)\n- Added `LifecycleConfig` struct with `setup_commands`, `setup_command_timeout_ms`, and `devcontainer_phases`\n- Added `run_with_lifecycle()` method that:\n 1. Calls `sandbox.initialize()`\n 2. Fires `SandboxReady` hook (blocking — can abort run)\n 3. Emits `SandboxInitialized` event\n 4. Runs remote git setup if sandbox is remote and config doesn't already have git info\n 5. Runs setup commands inside sandbox\n 6. Runs devcontainer lifecycle phases inside sandbox\n 7. Calls `run_internal()` (or checkpoint resume path)\n- Added `cleanup_sandbox()` method that fires `SandboxCleanup` hook and conditionally cleans up\n- Added 5 tests for the new methods:\n - `run_with_lifecycle_fires_sandbox_initialized_event`\n - `run_with_lifecycle_runs_setup_commands`\n - `run_with_lifecycle_setup_failure_aborts_run`\n - `cleanup_sandbox_fires_hook`\n - `run_with_lifecycle_emits_events_in_order`\n\n### 4. `lib/crates/fabro-workflows/src/cli/run.rs`\n- **`run_command`**: \n - Moved `ReadBeforeWriteSandbox` wrapping before engine construction\n - Removed inline `sandbox.initialize()`, remote git setup, setup commands, devcontainer lifecycle\n - Added `SandboxInitialized` event listener (registered before emitter Arc wrapping) that writes `sandbox.json` and updates progress UI\n - Added SSH access listener\n - Builds `LifecycleConfig` and calls `engine.run_with_lifecycle()` instead of `engine.run()`\n - Replaced inline cleanup with `engine.cleanup_sandbox()`\n - Added `FinalizeConfig` struct to capture config fields needed after `run_with_lifecycle` consumes config\n- **`run_from_branch`**: \n - Moved `ReadBeforeWriteSandbox` wrapping before engine construction\n - Remote sandbox init + branch checkout converted to setup_commands in `LifecycleConfig`\n - Uses `run_with_lifecycle()` instead of `run_from_checkpoint()`\n - Added `engine.cleanup_sandbox()` call (previously just did `sandbox.cleanup()`)\n - Added `FinalizeConfig` for post-run operations\n- Removed `setup_remote_git()` function (moved to engine.rs)\n- Added `FinalizeConfig` struct and `write_finalize_commit_from()` function\n\n### 5. `docs/agents/hooks.mdx`\n- Updated `sandbox_ready` to show \"Yes\" for blocking by default\n- Updated description to \"After the sandbox is initialized and ready\"\n- Added `sandbox_ready` to the \"Blocking by default\" list", @@ -49,8 +54,8 @@ "thread.implement.current_node": "simplify_opus", "response.simplify_gemini": "Everything passes. Here's a summary of what was fixed:\n\n## Summary\n\n### Fixed Issues\n\n1. **Stringly-typed provider comparison** (`cli/run.rs`): Replaced `provider_name == \"docker\"` and `provider_name == \"ssh\"` string comparisons with `provider == SandboxProvider::Docker` and `provider == SandboxProvider::Ssh` enum comparisons. This eliminated the intermediate `sandbox_provider_name` match arm and the `provider_name: String` allocation, using the `Copy`-implementing `SandboxProvider` enum directly in the event listener closure.\n\n2. **Test boilerplate** (`engine.rs`): Extracted `test_run_config(run_dir, run_id)` and `test_lifecycle(setup_commands)` helper functions that build default `RunConfig` and `LifecycleConfig` for tests. The 5 new lifecycle tests each had ~20 lines of identical config construction that now reduce to single-line calls. This removed ~95 lines of duplicated test code.\n\n### Findings Not Fixed (by design)\n\n- **`FinalizeConfig`**: While it copies fields from `RunConfig`, it serves a genuine purpose — the error path needs config values when `run_with_lifecycle` fails and doesn't return a `RunConfig`. Eliminating it would require restructuring the entire post-engine control flow, which would be a larger refactor with no functional benefit.\n- **`deferred_sandbox` pattern (`Arc>>>`**: This is inherently needed because event listeners are registered before the sandbox is created, but need access to it later. The sandbox can't be created earlier (it depends on provider config), and the listeners must be registered before the emitter is wrapped in `Arc`. The pattern is local to this scope and the mutex is only locked once (when the event fires).\n- **Existing 43 `RunConfig` constructions in tests**: The new helpers only apply to the 5 new tests. Backfilling all existing tests would be scope creep unrelated to this PR.", "internal.fidelity": "compact", - "last_stage": "simplify_gemini", - "internal.thread_id": "simplify_opus", + "last_stage": "simplify_gpt", + "internal.thread_id": "simplify_gemini", "internal.retry_count.implement": 1 }, "logs": [], @@ -68,24 +73,6 @@ "status": "success", "duration_ms": 0 }, - "preflight_compile": { - "status": "success", - "context_updates": { - "command.stderr": "", - "command.output": "" - }, - "notes": "Script completed: cargo check -q --workspace 2>&1", - "duration_ms": 72138 - }, - "preflight_lint": { - "status": "success", - "context_updates": { - "command.stderr": "", - "command.output": "" - }, - "notes": "Script completed: cargo clippy -q --workspace -- -D warnings 2>&1", - "duration_ms": 16704 - }, "simplify_opus": { "status": "success", "context_updates": { @@ -109,6 +96,52 @@ ], "duration_ms": 651106 }, + "simplify_gemini": { + "status": "success", + "context_updates": { + "last_response": "Everything passes. Here's a summary of what was fixed:\n\n## Summary\n\n### Fixed Issues\n\n1. **Stringly-typed provider comparison** (`cli/run.rs`): Replaced `provider_name == \"docker\"` and `provider_name ", + "last_stage": "simplify_gemini", + "response.simplify_gemini": "Everything passes. Here's a summary of what was fixed:\n\n## Summary\n\n### Fixed Issues\n\n1. **Stringly-typed provider comparison** (`cli/run.rs`): Replaced `provider_name == \"docker\"` and `provider_name == \"ssh\"` string comparisons with `provider == SandboxProvider::Docker` and `provider == SandboxProvider::Ssh` enum comparisons. This eliminated the intermediate `sandbox_provider_name` match arm and the `provider_name: String` allocation, using the `Copy`-implementing `SandboxProvider` enum directly in the event listener closure.\n\n2. **Test boilerplate** (`engine.rs`): Extracted `test_run_config(run_dir, run_id)` and `test_lifecycle(setup_commands)` helper functions that build default `RunConfig` and `LifecycleConfig` for tests. The 5 new lifecycle tests each had ~20 lines of identical config construction that now reduce to single-line calls. This removed ~95 lines of duplicated test code.\n\n### Findings Not Fixed (by design)\n\n- **`FinalizeConfig`**: While it copies fields from `RunConfig`, it serves a genuine purpose — the error path needs config values when `run_with_lifecycle` fails and doesn't return a `RunConfig`. Eliminating it would require restructuring the entire post-engine control flow, which would be a larger refactor with no functional benefit.\n- **`deferred_sandbox` pattern (`Arc>>>`**: This is inherently needed because event listeners are registered before the sandbox is created, but need access to it later. The sandbox can't be created earlier (it depends on provider config), and the listeners must be registered before the emitter is wrapped in `Arc`. The pattern is local to this scope and the mutex is only locked once (when the event fires).\n- **Existing 43 `RunConfig` constructions in tests**: The new helpers only apply to the 5 new tests. Backfilling all existing tests would be scope creep unrelated to this PR." + }, + "notes": "Stage completed: simplify_gemini", + "usage": { + "model": "claude-opus-4-6", + "input_tokens": 91954, + "output_tokens": 17985, + "cache_read_tokens": 3146696, + "cache_write_tokens": 106316, + "reasoning_tokens": 1093, + "cost": 2.728185 + }, + "files_touched": [ + "/home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs", + "/home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs" + ], + "duration_ms": 494013 + }, + "simplify_gpt": { + "status": "success", + "context_updates": { + "response.simplify_gpt": "All clean. Here's a summary of what was fixed:\n\n## Summary of Changes\n\n### Fixed Issues\n\n1. **Eliminated `FinalizeConfig` struct (−52 lines)** — Changed `run_with_lifecycle` to take `config: &mut RunConfig` instead of consuming `config: RunConfig` by value. This means:\n - The caller retains ownership of `RunConfig` and can read any fields mutated by remote git setup (e.g., `run_branch`, `base_sha`) directly after the call\n - Deleted the entire `FinalizeConfig` struct, its `from_run_config()` and `from_run_config_owned()` constructors\n - Renamed `write_finalize_commit_from(&FinalizeConfig)` back to `write_finalize_commit(&RunConfig)`\n - Simplified all `match &engine_result { Ok((ref o, _)) => ... }` to `match &engine_result { Ok(ref o) => ... }`\n - Eliminated all `finalize_config.field` references, using `config.field` directly\n - The error path is now actually more correct: if remote git setup succeeded but a later step failed, the caller still sees the populated metadata branch fields (previously they were reset to `None` in `from_run_config_owned`)\n\n2. **Eliminated duplicated `run_internal` calls in `run_with_lifecycle` (−12 lines)** — Step 7 was manually calling `run_internal` with identical logic to the existing `run()` and `run_from_checkpoint()` methods. Now it simply delegates to those existing public methods.\n\n3. **Fixed misleading `_ssh_command` variable name** — The variable is used in the `tracing::info!` macro, so the leading underscore was incorrect. Changed to `ssh_command`.\n\n**Net impact: −83 lines** (44 insertions, 127 deletions across the cleanup diff)", + "last_stage": "simplify_gpt", + "last_response": "All clean. Here's a summary of what was fixed:\n\n## Summary of Changes\n\n### Fixed Issues\n\n1. **Eliminated `FinalizeConfig` struct (−52 lines)** — Changed `run_with_lifecycle` to take `config: &mut " + }, + "notes": "Stage completed: simplify_gpt", + "usage": { + "model": "claude-opus-4-6", + "input_tokens": 81853, + "output_tokens": 21496, + "cache_read_tokens": 4764078, + "cache_write_tokens": 98079, + "reasoning_tokens": 2063, + "cost": 2.839995 + }, + "files_touched": [ + "/home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs", + "/home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs" + ], + "duration_ms": 619556 + }, "implement": { "status": "success", "context_updates": { @@ -135,38 +168,34 @@ ], "duration_ms": 1314327 }, - "simplify_gemini": { + "preflight_compile": { "status": "success", "context_updates": { - "last_response": "Everything passes. Here's a summary of what was fixed:\n\n## Summary\n\n### Fixed Issues\n\n1. **Stringly-typed provider comparison** (`cli/run.rs`): Replaced `provider_name == \"docker\"` and `provider_name ", - "last_stage": "simplify_gemini", - "response.simplify_gemini": "Everything passes. Here's a summary of what was fixed:\n\n## Summary\n\n### Fixed Issues\n\n1. **Stringly-typed provider comparison** (`cli/run.rs`): Replaced `provider_name == \"docker\"` and `provider_name == \"ssh\"` string comparisons with `provider == SandboxProvider::Docker` and `provider == SandboxProvider::Ssh` enum comparisons. This eliminated the intermediate `sandbox_provider_name` match arm and the `provider_name: String` allocation, using the `Copy`-implementing `SandboxProvider` enum directly in the event listener closure.\n\n2. **Test boilerplate** (`engine.rs`): Extracted `test_run_config(run_dir, run_id)` and `test_lifecycle(setup_commands)` helper functions that build default `RunConfig` and `LifecycleConfig` for tests. The 5 new lifecycle tests each had ~20 lines of identical config construction that now reduce to single-line calls. This removed ~95 lines of duplicated test code.\n\n### Findings Not Fixed (by design)\n\n- **`FinalizeConfig`**: While it copies fields from `RunConfig`, it serves a genuine purpose — the error path needs config values when `run_with_lifecycle` fails and doesn't return a `RunConfig`. Eliminating it would require restructuring the entire post-engine control flow, which would be a larger refactor with no functional benefit.\n- **`deferred_sandbox` pattern (`Arc>>>`**: This is inherently needed because event listeners are registered before the sandbox is created, but need access to it later. The sandbox can't be created earlier (it depends on provider config), and the listeners must be registered before the emitter is wrapped in `Arc`. The pattern is local to this scope and the mutex is only locked once (when the event fires).\n- **Existing 43 `RunConfig` constructions in tests**: The new helpers only apply to the 5 new tests. Backfilling all existing tests would be scope creep unrelated to this PR." + "command.stderr": "", + "command.output": "" }, - "notes": "Stage completed: simplify_gemini", - "usage": { - "model": "claude-opus-4-6", - "input_tokens": 91954, - "output_tokens": 17985, - "cache_read_tokens": 3146696, - "cache_write_tokens": 106316, - "reasoning_tokens": 1093, - "cost": 2.728185 + "notes": "Script completed: cargo check -q --workspace 2>&1", + "duration_ms": 72138 + }, + "preflight_lint": { + "status": "success", + "context_updates": { + "command.stderr": "", + "command.output": "" }, - "files_touched": [ - "/home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs", - "/home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs" - ], - "duration_ms": 494013 + "notes": "Script completed: cargo clippy -q --workspace -- -D warnings 2>&1", + "duration_ms": 16704 } }, - "next_node_id": "simplify_gpt", + "next_node_id": "verify", "node_visits": { "preflight_compile": 1, "toolchain": 1, "implement": 1, - "simplify_opus": 1, + "simplify_gpt": 1, "start": 1, "preflight_lint": 1, + "simplify_opus": 1, "simplify_gemini": 1 } } \ No newline at end of file diff --git a/nodes/simplify_gemini/diff.patch b/nodes/simplify_gemini/diff.patch new file mode 100644 index 000000000..e6a207c40 --- /dev/null +++ b/nodes/simplify_gemini/diff.patch @@ -0,0 +1,250 @@ +diff --git a/lib/crates/fabro-workflows/src/cli/run.rs b/lib/crates/fabro-workflows/src/cli/run.rs +index 4df34b9..806d1ae 100644 +--- a/lib/crates/fabro-workflows/src/cli/run.rs ++++ b/lib/crates/fabro-workflows/src/cli/run.rs +@@ -803,20 +803,12 @@ pub async fn run_command( + + // Register SandboxInitialized listener (must happen before emitter is wrapped in Arc) + { +- let sandbox_provider_name = match sandbox_provider { +- SandboxProvider::Local => "local", +- SandboxProvider::Docker => "docker", +- SandboxProvider::Daytona => "daytona", +- #[cfg(feature = "exedev")] +- SandboxProvider::Exe => "exe", +- SandboxProvider::Ssh => "ssh", +- }; + let run_dir_for_listener = run_dir.clone(); + let progress_for_listener = Arc::clone(&progress_ui); + let cwd_for_listener = cwd.to_string_lossy().to_string(); + let ssh_data_host = ssh_config.as_ref().map(|c| c.destination.clone()); + let deferred_sb = Arc::clone(&deferred_sandbox); +- let provider_name = sandbox_provider_name.to_string(); ++ let provider = sandbox_provider; // Copy — captured by move closure + emitter.on_event(move |event| { + if let crate::event::WorkflowRunEvent::SandboxInitialized { working_directory } = event + { +@@ -835,21 +827,22 @@ pub async fn run_command( + } + }); + ++ let is_docker = provider == SandboxProvider::Docker; + let record = crate::sandbox_record::SandboxRecord { +- provider: provider_name.clone(), ++ provider: provider.to_string(), + working_directory: working_directory.clone(), + identifier: sandbox_info_opt, +- host_working_directory: if provider_name == "docker" { ++ host_working_directory: if is_docker { + Some(cwd_for_listener.clone()) + } else { + None + }, +- container_mount_point: if provider_name == "docker" { ++ container_mount_point: if is_docker { + Some(working_directory.clone()) + } else { + None + }, +- data_host: if provider_name == "ssh" { ++ data_host: if provider == SandboxProvider::Ssh { + ssh_data_host.clone() + } else { + None +diff --git a/lib/crates/fabro-workflows/src/engine.rs b/lib/crates/fabro-workflows/src/engine.rs +index 3dcefa2..f01f447 100644 +--- a/lib/crates/fabro-workflows/src/engine.rs ++++ b/lib/crates/fabro-workflows/src/engine.rs +@@ -5671,24 +5671,12 @@ mod tests { + ); + } + +- #[tokio::test] +- async fn run_with_lifecycle_fires_sandbox_initialized_event() { +- let dir = tempfile::tempdir().unwrap(); +- let g = simple_graph(); +- +- let events = Arc::new(std::sync::Mutex::new(Vec::::new())); +- let events_clone = events.clone(); +- let mut emitter = EventEmitter::new(); +- emitter.on_event(move |event| { +- events_clone.lock().unwrap().push(event.clone()); +- }); +- +- let engine = WorkflowRunEngine::new(make_registry(), Arc::new(emitter), local_env()); +- let config = RunConfig { +- run_dir: dir.path().to_path_buf(), ++ fn test_run_config(run_dir: &std::path::Path, run_id: &str) -> RunConfig { ++ RunConfig { ++ run_dir: run_dir.to_path_buf(), + cancel_token: None, + dry_run: false, +- run_id: "lifecycle-test".into(), ++ run_id: run_id.into(), + git_checkpoint_enabled: false, + host_repo_path: None, + base_sha: None, +@@ -5703,14 +5691,37 @@ mod tests { + pull_request_draft: false, + asset_globs: Vec::new(), + workflow_slug: None, +- }; +- let lifecycle = LifecycleConfig { +- setup_commands: Vec::new(), ++ } ++ } ++ ++ fn test_lifecycle(setup_commands: Vec) -> LifecycleConfig { ++ LifecycleConfig { ++ setup_commands, + setup_command_timeout_ms: 300_000, + devcontainer_phases: Vec::new(), +- }; ++ } ++ } ++ ++ #[tokio::test] ++ async fn run_with_lifecycle_fires_sandbox_initialized_event() { ++ let dir = tempfile::tempdir().unwrap(); ++ let g = simple_graph(); ++ ++ let events = Arc::new(std::sync::Mutex::new(Vec::::new())); ++ let events_clone = events.clone(); ++ let mut emitter = EventEmitter::new(); ++ emitter.on_event(move |event| { ++ events_clone.lock().unwrap().push(event.clone()); ++ }); ++ ++ let engine = WorkflowRunEngine::new(make_registry(), Arc::new(emitter), local_env()); + let (outcome, _) = engine +- .run_with_lifecycle(&g, config, lifecycle, None) ++ .run_with_lifecycle( ++ &g, ++ test_run_config(dir.path(), "lifecycle-test"), ++ test_lifecycle(Vec::new()), ++ None, ++ ) + .await + .unwrap(); + assert_eq!(outcome.status, StageStatus::Success); +@@ -5739,33 +5750,13 @@ mod tests { + }); + + let engine = WorkflowRunEngine::new(make_registry(), Arc::new(emitter), local_env()); +- let config = RunConfig { +- run_dir: dir.path().to_path_buf(), +- cancel_token: None, +- dry_run: false, +- run_id: "setup-test".into(), +- git_checkpoint_enabled: false, +- host_repo_path: None, +- base_sha: None, +- run_branch: None, +- meta_branch: None, +- labels: HashMap::new(), +- checkpoint_exclude_globs: Vec::new(), +- github_app: None, +- git_author: crate::git::GitAuthor::default(), +- base_branch: None, +- pull_request_enabled: false, +- pull_request_draft: false, +- asset_globs: Vec::new(), +- workflow_slug: None, +- }; +- let lifecycle = LifecycleConfig { +- setup_commands: vec!["echo hello".to_string()], +- setup_command_timeout_ms: 300_000, +- devcontainer_phases: Vec::new(), +- }; + let (outcome, _) = engine +- .run_with_lifecycle(&g, config, lifecycle, None) ++ .run_with_lifecycle( ++ &g, ++ test_run_config(dir.path(), "setup-test"), ++ test_lifecycle(vec!["echo hello".to_string()]), ++ None, ++ ) + .await + .unwrap(); + assert_eq!(outcome.status, StageStatus::Success); +@@ -5788,32 +5779,14 @@ mod tests { + + let engine = + WorkflowRunEngine::new(make_registry(), Arc::new(EventEmitter::new()), local_env()); +- let config = RunConfig { +- run_dir: dir.path().to_path_buf(), +- cancel_token: None, +- dry_run: false, +- run_id: "setup-fail-test".into(), +- git_checkpoint_enabled: false, +- host_repo_path: None, +- base_sha: None, +- run_branch: None, +- meta_branch: None, +- labels: HashMap::new(), +- checkpoint_exclude_globs: Vec::new(), +- github_app: None, +- git_author: crate::git::GitAuthor::default(), +- base_branch: None, +- pull_request_enabled: false, +- pull_request_draft: false, +- asset_globs: Vec::new(), +- workflow_slug: None, +- }; +- let lifecycle = LifecycleConfig { +- setup_commands: vec!["exit 1".to_string()], +- setup_command_timeout_ms: 300_000, +- devcontainer_phases: Vec::new(), +- }; +- let result = engine.run_with_lifecycle(&g, config, lifecycle, None).await; ++ let result = engine ++ .run_with_lifecycle( ++ &g, ++ test_run_config(dir.path(), "setup-fail-test"), ++ test_lifecycle(vec!["exit 1".to_string()]), ++ None, ++ ) ++ .await; + assert!(result.is_err()); + let err = result.err().unwrap().to_string(); + assert!( +@@ -5852,33 +5825,13 @@ mod tests { + }); + + let engine = WorkflowRunEngine::new(make_registry(), Arc::new(emitter), local_env()); +- let config = RunConfig { +- run_dir: dir.path().to_path_buf(), +- cancel_token: None, +- dry_run: false, +- run_id: "order-test".into(), +- git_checkpoint_enabled: false, +- host_repo_path: None, +- base_sha: None, +- run_branch: None, +- meta_branch: None, +- labels: HashMap::new(), +- checkpoint_exclude_globs: Vec::new(), +- github_app: None, +- git_author: crate::git::GitAuthor::default(), +- base_branch: None, +- pull_request_enabled: false, +- pull_request_draft: false, +- asset_globs: Vec::new(), +- workflow_slug: None, +- }; +- let lifecycle = LifecycleConfig { +- setup_commands: vec!["echo ok".to_string()], +- setup_command_timeout_ms: 300_000, +- devcontainer_phases: Vec::new(), +- }; + engine +- .run_with_lifecycle(&g, config, lifecycle, None) ++ .run_with_lifecycle( ++ &g, ++ test_run_config(dir.path(), "order-test"), ++ test_lifecycle(vec!["echo ok".to_string()]), ++ None, ++ ) + .await + .unwrap(); + diff --git a/nodes/simplify_gpt/prompt.md b/nodes/simplify_gpt/prompt.md new file mode 100644 index 000000000..f32c86875 --- /dev/null +++ b/nodes/simplify_gpt/prompt.md @@ -0,0 +1,211 @@ +Goal: # Plan: Move sandbox lifecycle into the engine + +## Context + +`SandboxReady` and `SandboxCleanup` hook events are defined in `HookEvent` but never fired. They can't fire naturally because sandbox init/cleanup happens in `cli/run.rs` — outside the engine where all other hooks fire. The root cause is that `cli/run.rs` is a ~2000-line god function orchestrating everything: sandbox creation, init, setup commands, devcontainer lifecycle, engine construction, engine run, retro, PR creation, and cleanup. The engine receives an already-initialized sandbox and has no role in lifecycle management. + +This refactor moves sandbox initialization and setup into the engine so `SandboxReady` fires naturally alongside `RunStart`. Cleanup stays callable from the CLI (the retro agent needs the sandbox alive after the graph completes) but fires through an engine method so `SandboxCleanup` also uses the hook infrastructure. + +## Design + +### Two new engine methods + +**`run_with_lifecycle(graph, config, lifecycle, checkpoint?) -> Result`** +1. `sandbox.initialize()` +2. Fire `SandboxReady` hook (blocking — can abort run) +3. Emit `SandboxInitialized` event (CLI listener writes `sandbox.json`, updates progress UI) +4. Remote git setup if `sandbox.is_remote()` — produces `base_sha`, `run_branch`, `base_branch`, merged into `config` +5. Run setup commands inside sandbox +6. Run devcontainer lifecycle phases inside sandbox +7. Call existing `run_internal()` (unchanged — fires RunStart → graph → RunComplete) +8. Return outcome (sandbox still alive) + +**`cleanup_sandbox(run_id, workflow_name, preserve) -> Result<()>`** +1. Fire `SandboxCleanup` hook (non-blocking) +2. If `!preserve`: call `sandbox.cleanup()` + +Existing `run()` is unchanged — API server and integration tests keep using it with pre-initialized sandboxes. + +### New config struct + +```rust +// engine.rs +pub struct LifecycleConfig { + pub setup_commands: Vec, + pub setup_command_timeout_ms: u64, + pub devcontainer_phases: Vec<(String, Vec)>, +} +``` + +`run_with_lifecycle` takes `config: RunConfig` by value (currently `&RunConfig`) so it can fill in remote git values. `run_internal` continues to take `&RunConfig`. + +### CLI flow after refactor + +``` +sandbox = create_sandbox() // unchanged +sandbox = ReadBeforeWriteSandbox::new(sandbox) // moved before init (delegate_sandbox! delegates initialize) +engine = build_engine(sandbox, hook_runner, ...) +outcome = engine.run_with_lifecycle(graph, config, lifecycle) +// retro, conclusion, PR creation — sandbox still alive +engine.cleanup_sandbox(run_id, workflow_name, preserve) +``` + +Single scopeguard around the entire block that calls `engine.cleanup_sandbox()` on panic. + +## Steps + +### 1. `hook/types.rs` — Make `SandboxReady` blocking by default +- Add `Self::SandboxReady` to `is_blocking_by_default()` match arm (line 29-32) +- `SandboxCleanup` stays non-blocking (correct default) + +### 2. `engine.rs` — Add `LifecycleConfig` struct and `run_with_lifecycle` method +- Define `LifecycleConfig` (setup_commands, setup_command_timeout_ms, devcontainer_phases) +- Add `pub async fn run_with_lifecycle(self, graph, config, lifecycle, checkpoint) -> Result` that: + - Calls `self.services.sandbox.initialize()` + - Fires `SandboxReady` hook via `self.run_hooks()` + - Emits `WorkflowRunEvent::SandboxInitialized { working_directory }` via emitter + - Calls remote git setup if `sandbox.is_remote()`, fills config.base_sha/run_branch/base_branch/git_checkpoint_enabled + - Runs setup commands via `sandbox.exec_command()`, emitting Setup* events + - Runs devcontainer lifecycle via `devcontainer_bridge::run_devcontainer_lifecycle()` + - Calls `self.run_internal()` (or `run_from_checkpoint` path) + - Returns outcome + +### 3. `engine.rs` — Add `cleanup_sandbox` method +- `pub async fn cleanup_sandbox(&self, run_id, workflow_name, preserve) -> Result<(), String>` +- Fires `SandboxCleanup` hook +- If `!preserve`: calls `self.services.sandbox.cleanup()` + +### 4. `engine.rs` — Move `setup_remote_git` from `cli/run.rs` +- Move the `setup_remote_git()` function (cli/run.rs line 1636-1679) into engine.rs +- It only uses `sandbox.exec_command()` and `run_id` — no CLI dependencies + +### 5. `event.rs` — Add `SandboxInitialized` event variant +- Add `WorkflowRunEvent::SandboxInitialized { working_directory: String }` variant +- This replaces the inline sandbox.json writing in cli/run.rs + +### 6. `cli/run.rs` — Register event listener for sandbox.json +- Before calling `run_with_lifecycle`, register a listener on the emitter for `SandboxInitialized` +- Listener captures the pre-built `SandboxRecord` template (all provider-specific fields filled, `working_directory` empty) +- On event: fill `working_directory` from event, call `record.save()` +- Also update progress UI `set_working_directory` in the same listener + +### 7. `cli/run.rs` — Refactor `run_command` to use new engine methods +- Move `ReadBeforeWriteSandbox` wrapping to before engine construction (currently at line 966, after init — delegate_sandbox! macro delegates initialize so wrapping before init works) +- Move `HookRunner` creation earlier (before engine construction) — currently line 1222, move to ~line 800 +- Remove: `sandbox.initialize()` (line 886), remote git setup (lines 982-996), setup commands (lines 1031-1072), devcontainer lifecycle (lines 1074-1091) +- Build `LifecycleConfig` from `setup_commands` and `devcontainer_config` +- Build `RunConfig` without remote git fields (leave base_sha/run_branch/base_branch as None for remote — engine fills them) +- Call `engine.run_with_lifecycle()` instead of `engine.run()` +- Replace cleanup section (lines 1587-1604) with `engine.cleanup_sandbox()` +- Replace two scopeguards with one that calls `engine.cleanup_sandbox()` on panic +- Remove `status_guard` for SandboxInitFailed — engine handles init errors + +### 8. `cli/run.rs` — Refactor `run_from_branch` to use new engine methods +- Use `run_with_lifecycle` with empty `LifecycleConfig` (no setup commands, no devcontainer) +- Add `cleanup_sandbox()` call (currently no scopeguard — this is an improvement) +- This gives the resume path hooks for free (currently has zero hooks) + +### 9. `docs/agents/hooks.mdx` — Update docs +- Remove any "reserved" annotations for `sandbox_ready` / `sandbox_cleanup` +- Note that `sandbox_ready` is blocking by default + +## Files to modify +- `lib/crates/fabro-workflows/src/hook/types.rs` — SandboxReady blocking default +- `lib/crates/fabro-workflows/src/engine.rs` — LifecycleConfig, run_with_lifecycle, cleanup_sandbox, setup_remote_git +- `lib/crates/fabro-workflows/src/event.rs` — SandboxInitialized event variant +- `lib/crates/fabro-workflows/src/cli/run.rs` — major simplification of run_command and run_from_branch +- `docs/agents/hooks.mdx` — remove "reserved" annotations + +## Files unchanged +- `lib/crates/fabro-workflows/src/handler/mod.rs` — EngineServices unchanged +- `lib/crates/fabro-workflows/src/hook/runner.rs` — handles any HookEvent generically +- `lib/crates/fabro-agent/src/sandbox.rs` — Sandbox trait unchanged +- `lib/crates/fabro-agent/src/read_before_write_sandbox.rs` — delegate_sandbox! already delegates initialize/cleanup +- All sandbox implementations — unchanged + +## Verification +1. `cargo build --workspace` — compile check +2. `cargo test --workspace` — all existing tests pass (existing `run()` path unchanged) +3. `cargo clippy --workspace -- -D warnings` — no new warnings +4. Manual test: `fabro run` with a workflow that has `sandbox_ready` and `sandbox_cleanup` hooks configured — verify hooks fire +5. Manual test: `fabro run --sandbox daytona` — verify remote git setup still works through the engine +6. Manual test: `fabro run` with `--preserve-sandbox` — verify cleanup is skipped but SandboxCleanup hook still fires + + +## Completed stages +- **toolchain**: success + - Script: `command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1` + - Stdout: + ``` + cargo 1.94.0 (85eff7c80 2026-01-15) + ``` + - Stderr: (empty) +- **preflight_compile**: success + - Script: `cargo check -q --workspace 2>&1` + - Stdout: (empty) + - Stderr: (empty) +- **preflight_lint**: success + - Script: `cargo clippy -q --workspace -- -D warnings 2>&1` + - Stdout: (empty) + - Stderr: (empty) +- **implement**: success + - Model: claude-opus-4-6, 172.3k tokens in / 48.5k out + - Files: /home/daytona/workspace/docs/agents/hooks.mdx, /home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/event.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/hook/types.rs +- **simplify_opus**: success + - Model: claude-opus-4-6, 90.5k tokens in / 16.9k out + - Files: /home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs +- **simplify_gemini**: success + - Model: claude-opus-4-6, 92.0k tokens in / 18.0k out + - Files: /home/daytona/workspace/lib/crates/fabro-workflows/src/cli/run.rs, /home/daytona/workspace/lib/crates/fabro-workflows/src/engine.rs + + +# Simplify: Code Review and Cleanup + +Review all changed files for reuse, quality, and efficiency. Fix any issues found. + +## Phase 1: Identify Changes + +Run git diff (or git diff HEAD if there are staged changes) to see what changed. If there are no git changes, review the most recently modified files that the user mentioned or that you edited earlier in this conversation. + +## Phase 2: Launch Three Review Agents in Parallel + +Use the Agent tool to launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context. + +### Agent 1: Code Reuse Review + +For each change: + +1. Search for existing utilities and helpers that could replace newly written code. Use Grep to find similar patterns elsewhere in the codebase — common locations are utility directories, shared modules, and files adjacent to the changed ones. +2. Flag any new function that duplicates existing functionality. Suggest the existing function to use instead. +3. Flag any inline logic that could use an existing utility — hand-rolled string manipulation, manual path handling, custom environment checks, ad-hoc type guards, and similar patterns are common candidates. + +Note: This is a greenfield app, so focus on maximizing simplicity and don't worry about changing things to achieve it. + +### Agent 2: Code Quality Review + +Review the same changes for hacky patterns: + +1. Redundant state: state that duplicates existing state, cached values that could be derived, observers/effects that could be direct calls +2. Parameter sprawl: adding new parameters to a function instead of generalizing or restructuring existing ones +3. Copy-paste with slight variation: near-duplicate code blocks that should be unified with a shared abstraction +4. Leaky abstractions: exposing internal details that should be encapsulated, or breaking existing abstraction boundaries +5. Stringly-typed code: using raw strings where constants, enums (string unions), or branded types already exist in the codebase + +Note: This is a greenfield app, so be aggressive in optimizing quality. + +### Agent 3: Efficiency Review + +Review the same changes for efficiency: + +1. Unnecessary work: redundant computations, repeated file reads, duplicate network/API calls, N+1 patterns +2. Missed concurrency: independent operations run sequentially when they could run in parallel +3. Hot-path bloat: new blocking work added to startup or per-request/per-render hot paths +4. Unnecessary existence checks: pre-checking file/resource existence before operating (TOCTOU anti-pattern) — operate directly and handle the error +5. Memory: unbounded data structures, missing cleanup, event listener leaks +6. Overly broad operations: reading entire files when only a portion is needed, loading all items when filtering for one + +## Phase 3: Fix Issues + +Wait for all three agents to complete. Aggregate their findings and fix each issue directly. If a finding is a false positive or not worth addressing, note it and move on — do not argue with the finding, just skip it. + +When done, briefly summarize what was fixed (or confirm the code was already clean). \ No newline at end of file diff --git a/nodes/simplify_gpt/provider_used.json b/nodes/simplify_gpt/provider_used.json new file mode 100644 index 000000000..c1905ff10 --- /dev/null +++ b/nodes/simplify_gpt/provider_used.json @@ -0,0 +1,5 @@ +{ + "mode": "agent", + "provider": "anthropic", + "model": "claude-opus-4-6" +} \ No newline at end of file diff --git a/nodes/simplify_gpt/response.md b/nodes/simplify_gpt/response.md new file mode 100644 index 000000000..697665dcb --- /dev/null +++ b/nodes/simplify_gpt/response.md @@ -0,0 +1,19 @@ +All clean. Here's a summary of what was fixed: + +## Summary of Changes + +### Fixed Issues + +1. **Eliminated `FinalizeConfig` struct (−52 lines)** — Changed `run_with_lifecycle` to take `config: &mut RunConfig` instead of consuming `config: RunConfig` by value. This means: + - The caller retains ownership of `RunConfig` and can read any fields mutated by remote git setup (e.g., `run_branch`, `base_sha`) directly after the call + - Deleted the entire `FinalizeConfig` struct, its `from_run_config()` and `from_run_config_owned()` constructors + - Renamed `write_finalize_commit_from(&FinalizeConfig)` back to `write_finalize_commit(&RunConfig)` + - Simplified all `match &engine_result { Ok((ref o, _)) => ... }` to `match &engine_result { Ok(ref o) => ... }` + - Eliminated all `finalize_config.field` references, using `config.field` directly + - The error path is now actually more correct: if remote git setup succeeded but a later step failed, the caller still sees the populated metadata branch fields (previously they were reset to `None` in `from_run_config_owned`) + +2. **Eliminated duplicated `run_internal` calls in `run_with_lifecycle` (−12 lines)** — Step 7 was manually calling `run_internal` with identical logic to the existing `run()` and `run_from_checkpoint()` methods. Now it simply delegates to those existing public methods. + +3. **Fixed misleading `_ssh_command` variable name** — The variable is used in the `tracing::info!` macro, so the leading underscore was incorrect. Changed to `ssh_command`. + +**Net impact: −83 lines** (44 insertions, 127 deletions across the cleanup diff) \ No newline at end of file diff --git a/nodes/simplify_gpt/status.json b/nodes/simplify_gpt/status.json new file mode 100644 index 000000000..003ffd4b4 --- /dev/null +++ b/nodes/simplify_gpt/status.json @@ -0,0 +1,6 @@ +{ + "status": "success", + "notes": "Stage completed: simplify_gpt", + "failure_reason": null, + "timestamp": "2026-03-16T05:01:09.791865+00:00" +} \ No newline at end of file