bevy-agent-feedback-plugin 0.5.0

Let AI coding agents see and control your Bevy app: input injection, labeled screenshots, and frame-synced feedback over a JSON-lines TCP protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
use super::*;
use args::RequiredWindowSize;
use bevy_agent_feedback_plugin::client::CaptureWindowInfo;

#[derive(serde::Serialize)]
struct RunSummary {
    schema_version: u8,
    result: RunResult,
    phase: &'static str,
    elapsed_ms: u128,
    timings_ms: std::collections::BTreeMap<&'static str, u128>,
    launch: LaunchSummary,
    artifacts: ArtifactSummary,
    window: WindowSummary,
    process_exit: &'static str,
    teardown: TeardownSummary,
    warnings: Vec<String>,
}

#[derive(serde::Serialize)]
struct RunResult {
    success: bool,
    code: &'static str,
    message: String,
}

#[derive(serde::Serialize)]
struct LaunchSummary {
    prepare_command: Option<Vec<String>>,
    game_command: Vec<String>,
    driver_command: Option<Vec<String>>,
    caller_cwd: PathBuf,
    game_cwd: PathBuf,
}

#[derive(serde::Serialize)]
struct ArtifactSummary {
    directory: PathBuf,
    run_summary: PathBuf,
    failure_summary: Option<PathBuf>,
    game_log: PathBuf,
    prepare_log: Option<PathBuf>,
    driver_log: Option<PathBuf>,
    protocol: PathBuf,
    transcript: PathBuf,
    screenshots: PathBuf,
}

#[derive(serde::Serialize)]
struct WindowSummary {
    required_logical: Option<RequiredWindowSize>,
    actual: Option<CaptureWindowInfo>,
}

#[derive(serde::Serialize)]
struct TeardownSummary {
    input_release: &'static str,
    shutdown_acknowledgment: &'static str,
    socket_closure: &'static str,
    child_exit: &'static str,
    forced_termination: bool,
}

impl Default for TeardownSummary {
    fn default() -> Self {
        Self {
            input_release: "not_attempted",
            shutdown_acknowledgment: "not_attempted",
            socket_closure: "not_attempted",
            child_exit: "not_attempted",
            forced_termination: false,
        }
    }
}

struct RunFailure {
    phase: &'static str,
    code: &'static str,
    message: String,
}

pub(super) fn run(args: RunArgs) -> Result<(), String> {
    let started = Instant::now();
    let caller_cwd = std::env::current_dir().map_err(|error| error.to_string())?;
    let game_cwd = args.game_cwd.clone().unwrap_or_else(|| caller_cwd.clone());
    fs::create_dir_all(&args.artifacts).map_err(|error| error.to_string())?;
    let game_log = args.artifacts.join("game.log");
    let prepare_log = args
        .prepare
        .as_ref()
        .map(|_| args.artifacts.join("prepare.log"));
    let driver_log_path = args
        .driver
        .as_ref()
        .map(|_| args.artifacts.join("driver.log"));
    let transcript_file = args.artifacts.join("transcript.jsonl");
    let protocol_artifact = args.artifacts.join("protocol.json");
    let screenshot_dir = args.artifacts.join("screenshots");
    let wrapper_capture_dir = args.artifacts.join("captures");
    let summary_path = args.artifacts.join("run-summary.json");
    let mut summary = RunSummary {
        schema_version: 1,
        result: RunResult {
            success: false,
            code: "runner_internal",
            message: String::new(),
        },
        phase: "setup",
        elapsed_ms: 0,
        timings_ms: std::collections::BTreeMap::new(),
        launch: LaunchSummary {
            prepare_command: args.prepare.clone(),
            game_command: args.game.clone(),
            driver_command: args.driver.clone(),
            caller_cwd,
            game_cwd: game_cwd.clone(),
        },
        artifacts: ArtifactSummary {
            directory: args.artifacts.clone(),
            run_summary: summary_path.clone(),
            failure_summary: None,
            game_log: game_log.clone(),
            prepare_log: prepare_log.clone(),
            driver_log: driver_log_path.clone(),
            protocol: protocol_artifact.clone(),
            transcript: transcript_file.clone(),
            screenshots: screenshot_dir.clone(),
        },
        window: WindowSummary {
            required_logical: args.required_window_size,
            actual: None,
        },
        process_exit: "not_started",
        teardown: TeardownSummary::default(),
        warnings: Vec::new(),
    };

    if args.used_legacy_ready_timeout {
        let warning = "--ready-timeout/BEVY_FEEDBACK_READY_TIMEOUT_MS is deprecated; use --protocol-timeout/BEVY_FEEDBACK_PROTOCOL_TIMEOUT_MS";
        eprintln!("bevy-feedback: warning: {warning}");
        summary.warnings.push(warning.to_string());
    }
    println!(
        "bevy-feedback launch: phase=setup game_command={:?} game_cwd={}",
        args.game,
        game_cwd.display()
    );

    let result = run_lifecycle(
        &args,
        &game_cwd,
        &game_log,
        prepare_log.as_deref(),
        driver_log_path.as_deref(),
        &transcript_file,
        &wrapper_capture_dir,
        &protocol_artifact,
        &screenshot_dir,
        &mut summary,
    );
    summary.elapsed_ms = started.elapsed().as_millis();
    let failure = match result {
        Ok(()) => {
            summary.result = RunResult {
                success: true,
                code: "ok",
                message: "run completed gracefully".to_string(),
            };
            summary.phase = "complete";
            None
        }
        Err(failure) => {
            summary.result = RunResult {
                success: false,
                code: failure.code,
                message: failure.message.clone(),
            };
            summary.phase = failure.phase;
            summary.artifacts.failure_summary = Some(args.artifacts.join("failure-summary.txt"));
            Some(failure)
        }
    };
    let summary_json = serde_json::to_vec_pretty(&summary).map_err(|error| error.to_string())?;
    fs::write(&summary_path, summary_json).map_err(|error| error.to_string())?;

    if let Some(failure) = failure {
        let report = evidence::render_failure(&failure, &summary);
        fs::write(args.artifacts.join("failure-summary.txt"), &report)
            .map_err(|error| error.to_string())?;
        Err(report)
    } else {
        println!(
            "bevy-feedback ok: phase=complete elapsed_ms={} artifacts={}",
            summary.elapsed_ms,
            args.artifacts.display()
        );
        println!(
            "teardown: inputs={} shutdown={} socket={} child={}",
            summary.teardown.input_release,
            summary.teardown.shutdown_acknowledgment,
            summary.teardown.socket_closure,
            summary.teardown.child_exit
        );
        Ok(())
    }
}

#[allow(clippy::too_many_arguments)]
fn run_lifecycle(
    args: &RunArgs,
    game_cwd: &Path,
    game_log: &Path,
    prepare_log: Option<&Path>,
    driver_log_path: Option<&Path>,
    transcript_file: &Path,
    wrapper_capture_dir: &Path,
    protocol_artifact: &Path,
    screenshot_dir: &Path,
    summary: &mut RunSummary,
) -> Result<(), RunFailure> {
    let phase_started = Instant::now();
    if let (Some(command), Some(log_path)) = (&args.prepare, prepare_log) {
        println!(
            "bevy-feedback phase=prepare command={command:?} cwd={}",
            summary.launch.caller_cwd.display()
        );
        let mut child =
            spawn_logged_command("--prepare", command, None, log_path).map_err(|message| {
                RunFailure {
                    phase: "prepare",
                    code: "prepare_spawn_failed",
                    message,
                }
            })?;
        match wait_child(&mut child, args.prepare_timeout).map_err(|error| RunFailure {
            phase: "prepare",
            code: "prepare_wait_failed",
            message: error.to_string(),
        })? {
            Some(status) if status.success() => {}
            Some(status) => {
                return Err(RunFailure {
                    phase: "prepare",
                    code: "prepare_nonzero_exit",
                    message: format!("prepare exited with status {status}"),
                });
            }
            None => {
                let _ = child.kill();
                let _ = child.wait();
                return Err(RunFailure {
                    phase: "prepare",
                    code: "prepare_timeout",
                    message: format!(
                        "prepare timed out after {} ms",
                        args.prepare_timeout.as_millis()
                    ),
                });
            }
        }
    }
    summary
        .timings_ms
        .insert("prepare", phase_started.elapsed().as_millis());

    let setup_started = Instant::now();
    let python =
        BundledPythonClient::materialize(&args.artifacts.join("python")).map_err(|error| {
            RunFailure {
                phase: "setup",
                code: "artifact_setup_failed",
                message: error.to_string(),
            }
        })?;
    if let Some(parent) = args
        .protocol_file
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        fs::create_dir_all(parent).map_err(|error| RunFailure {
            phase: "setup",
            code: "artifact_setup_failed",
            message: error.to_string(),
        })?;
    }
    let _ = fs::remove_file(&args.protocol_file);
    fs::create_dir_all(wrapper_capture_dir).map_err(|error| RunFailure {
        phase: "setup",
        code: "artifact_setup_failed",
        message: error.to_string(),
    })?;
    File::create(transcript_file).map_err(|error| RunFailure {
        phase: "setup",
        code: "artifact_setup_failed",
        message: error.to_string(),
    })?;
    let game_log_file = Arc::new(Mutex::new(File::create(game_log).map_err(|error| {
        RunFailure {
            phase: "setup",
            code: "artifact_setup_failed",
            message: error.to_string(),
        }
    })?));
    summary
        .timings_ms
        .insert("setup", setup_started.elapsed().as_millis());

    let spawn_started = Instant::now();
    println!(
        "bevy-feedback phase=game_spawn command={:?} cwd={}",
        args.game,
        game_cwd.display()
    );
    let mut game = spawn_command(
        "--game",
        &args.game,
        args,
        &python,
        wrapper_capture_dir,
        transcript_file,
        Some(game_cwd),
    )
    .map_err(|message| RunFailure {
        phase: "game_spawn",
        code: "game_spawn_failed",
        message,
    })?;
    stream_child_logs(&mut game, game_log_file);
    summary.process_exit = "running";
    summary
        .timings_ms
        .insert("game_spawn", spawn_started.elapsed().as_millis());

    let stop = Arc::new(AtomicBool::new(false));
    let stop_for_signal = stop.clone();
    let _ = ctrlc::set_handler(move || stop_for_signal.store(true, Ordering::Relaxed));

    let protocol_started = Instant::now();
    println!(
        "bevy-feedback phase=protocol_startup timeout_ms={}",
        args.protocol_timeout.as_millis()
    );
    let ready = match wait_ready(&args.protocol_file, args.protocol_timeout, &mut game, &stop) {
        Ok(ready) => ready,
        Err(error) => {
            summary
                .timings_ms
                .insert("protocol_startup", protocol_started.elapsed().as_millis());
            summary.process_exit = game
                .try_wait()
                .ok()
                .flatten()
                .as_ref()
                .map(exit_category)
                .unwrap_or("running");
            terminate_game(&mut game, summary);
            copy_if_exists(&args.protocol_file, protocol_artifact);
            let _ = copy_captures(wrapper_capture_dir, screenshot_dir);
            let code = if error.starts_with("game exited") {
                "protocol_early_exit"
            } else {
                "protocol_timeout"
            };
            return Err(RunFailure {
                phase: "protocol_startup",
                code,
                message: error,
            });
        }
    };
    summary
        .timings_ms
        .insert("protocol_startup", protocol_started.elapsed().as_millis());
    println!(
        "bevy-feedback ready: phase=driver session={} socket={} protocol={} elapsed_ms={} (protocol ready != game ready; use semantic readiness for animated games or strict stability for static scenes before capturing)",
        ready.session_id,
        ready.socket_addr,
        args.protocol_file.display(),
        protocol_started.elapsed().as_millis()
    );
    let live_capture_dir = ready
        .capture_dir
        .clone()
        .unwrap_or_else(|| wrapper_capture_dir.to_path_buf());

    let driver_started = Instant::now();
    let mut primary_failure = inspect_window(args, transcript_file, summary).err();
    if primary_failure.is_none()
        && let (Some(driver_command), Some(log_path)) = (&args.driver, driver_log_path)
    {
        primary_failure = run_driver(
            driver_command,
            log_path,
            args,
            &python,
            wrapper_capture_dir,
            transcript_file,
        )
        .err();
    } else if primary_failure.is_none() {
        match wait_game_or_signal(&mut game, &stop).map_err(|error| RunFailure {
            phase: "game",
            code: "game_wait_failed",
            message: error.to_string(),
        })? {
            Some(status) if status.success() => summary.process_exit = exit_category(&status),
            Some(status) => {
                primary_failure = Some(RunFailure {
                    phase: "game",
                    code: "game_nonzero_exit",
                    message: format!("game exited with status {status}"),
                })
            }
            None => {}
        }
    }
    summary
        .timings_ms
        .insert("driver", driver_started.elapsed().as_millis());

    let teardown_started = Instant::now();
    copy_if_exists(&args.protocol_file, protocol_artifact);
    teardown_game(
        &args.protocol_file,
        transcript_file,
        &mut game,
        args.shutdown_timeout,
        summary,
    );
    summary
        .timings_ms
        .insert("teardown", teardown_started.elapsed().as_millis());
    let screenshots =
        copy_captures(&live_capture_dir, screenshot_dir).map_err(|error| RunFailure {
            phase: "artifacts",
            code: "artifact_copy_failed",
            message: error.to_string(),
        })?;
    print_screenshots(&screenshots);

    if let Some(failure) = primary_failure {
        return Err(failure);
    }
    if summary.teardown.forced_termination {
        let message = "game required forced termination during teardown".to_string();
        return Err(RunFailure {
            phase: "teardown",
            code: "teardown_forced_termination",
            message,
        });
    }
    if matches!(summary.process_exit, "nonzero" | "signal") {
        let message = format!("game process exited with category {}", summary.process_exit);
        return Err(RunFailure {
            phase: "teardown",
            code: "game_nonzero_exit",
            message,
        });
    }
    if summary.teardown.shutdown_acknowledgment != "acknowledged" {
        summary
            .warnings
            .push("game exited cleanly before shutdown acknowledgment".to_string());
    }
    Ok(())
}

fn inspect_window(
    args: &RunArgs,
    transcript_file: &Path,
    summary: &mut RunSummary,
) -> Result<(), RunFailure> {
    let config = AgentClientConfig {
        protocol_file: args.protocol_file.clone(),
        transcript_file: Some(transcript_file.to_path_buf()),
        timeout: Duration::from_secs(2),
        ..Default::default()
    };
    let response =
        match AgentClient::with_config(config).and_then(|mut client| client.window_info()) {
            Ok(response) => response,
            Err(error) => {
                return unavailable_window(
                    format!("could not observe the primary window: {error}"),
                    args.required_window_size.is_some(),
                    summary,
                );
            }
        };
    let actual =
        match serde_json::from_value::<CaptureWindowInfo>(response["result"]["window"].clone()) {
            Ok(actual) => actual,
            Err(error) => {
                return unavailable_window(
                    format!("primary window dimensions were invalid: {error}"),
                    args.required_window_size.is_some(),
                    summary,
                );
            }
        };
    println!("{}", window_diagnostic(args.required_window_size, &actual));
    summary.window.actual = Some(actual.clone());
    if let Some(required) = args.required_window_size
        && (actual.logical_width != required.width as f32
            || actual.logical_height != required.height as f32)
    {
        return Err(RunFailure {
            phase: "environment",
            code: "window_size_mismatch",
            message: format!(
                "required logical window {}x{}, observed {}x{}",
                required.width, required.height, actual.logical_width, actual.logical_height
            ),
        });
    }
    Ok(())
}

fn unavailable_window(
    message: String,
    required: bool,
    summary: &mut RunSummary,
) -> Result<(), RunFailure> {
    if required {
        return Err(RunFailure {
            phase: "environment",
            code: "window_size_unavailable",
            message,
        });
    }
    eprintln!("bevy-feedback: warning: {message}");
    summary.warnings.push(message);
    Ok(())
}

fn window_diagnostic(required: Option<RequiredWindowSize>, actual: &CaptureWindowInfo) -> String {
    let required = required
        .map(|size| format!("{}x{}", size.width, size.height))
        .unwrap_or_else(|| "none".to_string());
    format!(
        "bevy-feedback window: required_logical={} actual_logical={}x{} actual_physical={}x{} scale_factor={}",
        required,
        actual.logical_width,
        actual.logical_height,
        actual.physical_width,
        actual.physical_height,
        actual.scale_factor
    )
}

fn run_driver(
    command: &[String],
    log_path: &Path,
    args: &RunArgs,
    python: &BundledPythonClient,
    capture_dir: &Path,
    transcript_file: &Path,
) -> Result<(), RunFailure> {
    let log_file = Arc::new(Mutex::new(File::create(log_path).map_err(|error| {
        RunFailure {
            phase: "driver",
            code: "driver_log_failed",
            message: error.to_string(),
        }
    })?));
    let mut driver = spawn_command(
        "--driver",
        command,
        args,
        python,
        capture_dir,
        transcript_file,
        None,
    )
    .map_err(|message| RunFailure {
        phase: "driver",
        code: "driver_spawn_failed",
        message,
    })?;
    stream_child_logs(&mut driver, log_file);
    match wait_child(&mut driver, args.driver_timeout).map_err(|error| RunFailure {
        phase: "driver",
        code: "driver_wait_failed",
        message: error.to_string(),
    })? {
        Some(status) if status.success() => Ok(()),
        Some(status) => Err(RunFailure {
            phase: "driver",
            code: "driver_nonzero_exit",
            message: format!("driver exited with status {status}"),
        }),
        None => {
            let _ = driver.kill();
            let _ = driver.wait();
            Err(RunFailure {
                phase: "driver",
                code: "driver_timeout",
                message: format!(
                    "driver timed out after {} ms",
                    args.driver_timeout.as_millis()
                ),
            })
        }
    }
}

mod evidence;
mod process;
#[cfg(test)]
pub(crate) use process::spawn_error;
use process::*;

#[cfg(test)]
mod tests;