rho-coding-agent 2.16.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
use super::{test_support::*, *};
use crate::workflow::*;
use pretty_assertions::assert_eq;
use std::{
    io::Write as _,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CompletionCrashPoint {
    TerminalAttempt,
    StructuredOutput,
    NodeFinished,
    SnapshotSaved,
    ScopeFinished,
    ScopeFinishedDuringCancellation,
}

// Covers: every durable completion boundary must recover without rerunning work.
// Owner: workflow crash recovery.
#[tokio::test]
async fn terminal_completion_recovers_at_each_crash_point() {
    for point in [
        CompletionCrashPoint::TerminalAttempt,
        CompletionCrashPoint::StructuredOutput,
        CompletionCrashPoint::NodeFinished,
        CompletionCrashPoint::SnapshotSaved,
        CompletionCrashPoint::ScopeFinished,
        CompletionCrashPoint::ScopeFinishedDuringCancellation,
    ] {
        let home = tempfile::tempdir().unwrap();
        let workspace = tempfile::tempdir().unwrap();
        let mut run =
            create_run_with_workflow(home.path(), workspace.path(), structured_workflow());
        let store = WorkflowStore::new(home.path()).unwrap();
        let directory = WorkflowLayout::new(home.path()).run(run.manifest.run_id);
        let attempt = AttemptNumber::new(1).unwrap();
        let node = task_id("inspect");
        let mut guard = store.lock_run(run.manifest.run_id).unwrap();
        for event in [
            WorkflowEvent::RunLifecycle {
                lifecycle: RunLifecycle::Running,
            },
            WorkflowEvent::NodeReady { node: node.clone() },
        ] {
            append_fixture_event(&store, &mut guard, &directory, &mut run, event);
        }
        let attempt_directory = attempt_directory(&directory, &node, attempt);
        std::fs::create_dir_all(&attempt_directory).unwrap();
        let output_artifact =
            artifacts::write_artifact(&directory, &attempt_directory.join("output.json"), b"true")
                .unwrap();
        let output = ValidatedOutputRef {
            artifact: output_artifact.clone(),
            value: WorkflowValue::Bool(true),
        };
        let completion = NodeCompletion {
            attempt: Some(attempt),
            outcome: NodeTerminalState::Success,
            cancellation_resume: None,
            command_exit: None,
            structured_output: Some(output.clone()),
            artifacts: AttemptArtifacts {
                structured_output: Some(output_artifact),
                ..AttemptArtifacts::default()
            },
        };
        artifacts::write_json(
            &directory,
            &attempt_directory.join("status.json"),
            &AttemptRecord {
                schema_version: ATTEMPT_VERSION,
                attempt,
                state: AttemptState::Completed {
                    completion: Box::new(completion.clone()),
                },
            },
        )
        .unwrap();
        for event in [
            WorkflowEvent::LaunchIntended {
                node: node.clone(),
                attempt,
            },
            WorkflowEvent::AttemptStarted {
                node: node.clone(),
                attempt,
                owner: ExternalOwner::Process { pid: 42 },
            },
        ] {
            append_fixture_event(&store, &mut guard, &directory, &mut run, event);
        }
        let structured = WorkflowEvent::StructuredOutput {
            node: node.clone(),
            attempt,
            output,
        };
        let finished = WorkflowEvent::NodeFinished {
            node,
            completion: Box::new(completion),
        };
        match point {
            CompletionCrashPoint::TerminalAttempt => {}
            CompletionCrashPoint::StructuredOutput | CompletionCrashPoint::NodeFinished => {
                let events = if point == CompletionCrashPoint::StructuredOutput {
                    vec![structured]
                } else {
                    vec![structured, finished]
                };
                for (offset, event) in events.into_iter().enumerate() {
                    store
                        .append_event(
                            &mut guard,
                            &WorkflowEventRecord {
                                schema_version: EVENT_VERSION,
                                sequence: run.state.last_event_sequence + offset as u64 + 1,
                                event,
                            },
                        )
                        .unwrap();
                }
            }
            CompletionCrashPoint::SnapshotSaved
            | CompletionCrashPoint::ScopeFinished
            | CompletionCrashPoint::ScopeFinishedDuringCancellation => {
                append_fixture_event(&store, &mut guard, &directory, &mut run, structured);
                append_fixture_event(&store, &mut guard, &directory, &mut run, finished);
                if point == CompletionCrashPoint::ScopeFinishedDuringCancellation {
                    append_fixture_event(
                        &store,
                        &mut guard,
                        &directory,
                        &mut run,
                        WorkflowEvent::CancellationRequested {
                            request_id: "00000000-0000-0000-0000-000000000007".into(),
                        },
                    );
                }
                if matches!(
                    point,
                    CompletionCrashPoint::ScopeFinished
                        | CompletionCrashPoint::ScopeFinishedDuringCancellation
                ) {
                    let scope = ScopeInstanceId::ROOT;
                    let result = scope_result(&run.graph, &run.state.state, scope)
                        .unwrap()
                        .unwrap();
                    append_fixture_event(
                        &store,
                        &mut guard,
                        &directory,
                        &mut run,
                        WorkflowEvent::ScopeFinished { scope, result },
                    );
                }
            }
        }
        drop(guard);
        let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
        let completed = runner(home.path(), workspace.path(), executor.clone())
            .drive(run.manifest.run_id, RecoveryDecision::NormalResume, None)
            .await
            .unwrap();
        assert_eq!(executor.0.load(Ordering::SeqCst), 0, "point: {point:?}");
        assert_eq!(
            terminal(&completed, "inspect"),
            Some(NodeTerminalState::Success),
            "point: {point:?}"
        );
        assert_eq!(
            root_output(&completed, "inspect"),
            &WorkflowValue::Bool(true),
            "point: {point:?}"
        );
        assert_eq!(
            completed.state.state.outcome(),
            Some(WorkflowOutcome::Success),
            "point: {point:?}"
        );
        let artifact = super::test_support::completion(&completed, "inspect")
            .artifacts
            .structured_output
            .as_ref()
            .unwrap();
        assert_eq!(artifact.retained_bytes, 4, "point: {point:?}");
        assert_eq!(
            artifact.observed,
            ArtifactObservation::Complete { observed_bytes: 4 },
            "point: {point:?}"
        );
        assert_replay(home.path(), &completed);
        if point == CompletionCrashPoint::SnapshotSaved {
            std::fs::write(directory.join(&artifact.relative_path), b"false").unwrap();
            assert!(matches!(
                store.load_run(completed.manifest.run_id),
                Err(WorkflowError::Corrupt { .. })
            ));
        }
    }
}

// Covers: append-only launch intents, partial attempt setup, and a started event
// without its snapshot must not lose attempt numbering or bypass confirmation.
// Owner: workflow launch crash recovery.
#[tokio::test]
async fn launch_recovers_at_each_durable_boundary() {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
    enum Point {
        Intent,
        IntentFile,
        StartedFile,
        StartedEvent,
        StartedSnapshot,
    }
    for point in [
        Point::Intent,
        Point::IntentFile,
        Point::StartedFile,
        Point::StartedEvent,
        Point::StartedSnapshot,
    ] {
        let home = tempfile::tempdir().unwrap();
        let workspace = tempfile::tempdir().unwrap();
        let run = create_run(home.path(), workspace.path());
        let run_id = run.manifest.run_id;
        let store = WorkflowStore::new(home.path()).unwrap();
        let guard = store.lock_run(run_id).unwrap();
        let directory = WorkflowLayout::new(home.path()).run(run_id);
        let mut journal = journal::RunJournal {
            store,
            guard,
            directory,
            run,
        };
        let node = task_id("inspect");
        let attempt = AttemptNumber::new(1).unwrap();
        journal
            .commit(WorkflowEvent::RunLifecycle {
                lifecycle: RunLifecycle::Running,
            })
            .unwrap();
        journal
            .commit(WorkflowEvent::NodeReady { node: node.clone() })
            .unwrap();
        let before_intent = journal.run.state.clone();
        journal
            .commit(WorkflowEvent::LaunchIntended {
                node: node.clone(),
                attempt,
            })
            .unwrap();
        assert_eq!(journal.store.load_run(run_id).unwrap().state, before_intent);
        let attempt_directory = attempt_directory(&journal.directory, &node, attempt);
        if point >= Point::IntentFile {
            std::fs::create_dir_all(&attempt_directory).unwrap();
            artifacts::write_json(
                &journal.directory,
                &attempt_directory.join("status.json"),
                &AttemptRecord {
                    schema_version: ATTEMPT_VERSION,
                    attempt,
                    state: if point >= Point::StartedFile {
                        AttemptState::Started {
                            owner: ExternalOwner::Process { pid: 42 },
                        }
                    } else {
                        AttemptState::LaunchIntended
                    },
                },
            )
            .unwrap();
        }
        let started = WorkflowEvent::AttemptStarted {
            node,
            attempt,
            owner: ExternalOwner::Process { pid: 42 },
        };
        if point == Point::StartedEvent {
            journal
                .store
                .append_event(
                    &mut journal.guard,
                    &WorkflowEventRecord {
                        schema_version: EVENT_VERSION,
                        sequence: journal.run.state.last_event_sequence + 1,
                        event: started,
                    },
                )
                .unwrap();
        } else if point == Point::StartedSnapshot {
            journal.commit(started).unwrap();
        }
        drop(journal);
        let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
        let normal = runner(home.path(), workspace.path(), executor.clone())
            .drive(run_id, RecoveryDecision::NormalResume, None)
            .await;
        let completed = if point >= Point::StartedEvent {
            assert!(
                matches!(normal, Err(RuntimeError::NeedsRecovery { .. })),
                "{point:?}"
            );
            assert_eq!(executor.0.load(Ordering::SeqCst), 0);
            runner(home.path(), workspace.path(), executor.clone())
                .drive(run_id, RecoveryDecision::ConfirmNoProcess, None)
                .await
                .unwrap()
        } else {
            normal.unwrap()
        };
        assert_eq!(executor.0.load(Ordering::SeqCst), 1);
        assert_eq!(
            completion(&completed, "inspect").attempt,
            Some(AttemptNumber::new(2).unwrap())
        );
        assert_replay(home.path(), &completed);
    }
}

// Covers: resume interrupted between cancellation cleanup writes must neither
// resurrect an acknowledged request nor erase a newer request after a crash.
// Owner: workflow cancellation recovery.
#[tokio::test]
async fn cancelled_resume_recovers_at_each_cleanup_boundary() {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
    enum Point {
        Reopened,
        Running,
        Reset,
        RequestRemoved,
        StateCleared,
        LegacyStateCleared,
        NewRequest,
    }
    for point in [
        Point::Reopened,
        Point::Running,
        Point::Reset,
        Point::RequestRemoved,
        Point::StateCleared,
        Point::LegacyStateCleared,
        Point::NewRequest,
    ] {
        let home = tempfile::tempdir().unwrap();
        let workspace = tempfile::tempdir().unwrap();
        let run = create_run(home.path(), workspace.path());
        let run_id = run.manifest.run_id;
        let cancelling = runner(home.path(), workspace.path(), Arc::new(SuccessfulExecutor));
        let receipt = cancelling.cancellation_request(run_id).request().unwrap();
        let cancelled = cancelling
            .drive(run_id, RecoveryDecision::NormalResume, None)
            .await
            .unwrap();
        assert_eq!(
            terminal(&cancelled, "inspect"),
            Some(NodeTerminalState::Cancellation)
        );
        assert!(cancellation_request_acknowledged(home.path(), run_id, &receipt).unwrap());
        let store = WorkflowStore::new(home.path()).unwrap();
        let guard = store.lock_run(run_id).unwrap();
        let directory = WorkflowLayout::new(home.path()).run(run_id);
        let mut journal = journal::RunJournal {
            store,
            guard,
            directory,
            run: cancelled,
        };
        journal
            .commit(WorkflowEvent::ScopeReopened {
                scope: ScopeInstanceId::ROOT,
            })
            .unwrap();
        if point >= Point::Running {
            journal
                .commit(WorkflowEvent::RunLifecycle {
                    lifecycle: RunLifecycle::Running,
                })
                .unwrap();
        }
        if point >= Point::Reset {
            journal
                .commit(WorkflowEvent::NodeReset {
                    node: task_id("inspect"),
                    reason: NodeResetReason::CleanCancellation,
                })
                .unwrap();
        }
        if point >= Point::RequestRemoved && point != Point::LegacyStateCleared {
            journal.store.clear_cancellation_request(run_id).unwrap();
        }
        if matches!(point, Point::StateCleared | Point::LegacyStateCleared) {
            journal.commit(WorkflowEvent::CancellationCleared).unwrap();
        }
        let newer = (point == Point::NewRequest)
            .then(|| request_cross_process_cancel(home.path(), run_id).unwrap());
        drop(journal);
        let executor = Arc::new(CountingExecutor(AtomicUsize::new(0)));
        let resumed = runner(home.path(), workspace.path(), executor.clone())
            .drive(run_id, RecoveryDecision::NormalResume, None)
            .await
            .unwrap();
        if let Some(newer) = newer {
            assert_ne!(newer, receipt);
            assert_eq!(
                terminal(&resumed, "inspect"),
                Some(NodeTerminalState::Cancellation)
            );
            assert!(cancellation_request_acknowledged(home.path(), run_id, &newer).unwrap());
            assert_eq!(executor.0.load(Ordering::SeqCst), 0);
        } else {
            assert_eq!(
                terminal(&resumed, "inspect"),
                Some(NodeTerminalState::Success),
                "{point:?}"
            );
            assert_eq!(executor.0.load(Ordering::SeqCst), 1);
        }
        assert_replay(home.path(), &resumed);
    }
}

// Covers: a flushed tail and a torn final line must replay before scheduling.
// Owner: workflow journal replay.
#[tokio::test]
async fn runner_replays_journal_tail() {
    let home = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let run = create_run(home.path(), workspace.path());
    let store = WorkflowStore::new(home.path()).unwrap();
    let mut guard = store.lock_run(run.manifest.run_id).unwrap();
    for (index, event) in [
        WorkflowEvent::RunLifecycle {
            lifecycle: RunLifecycle::Running,
        },
        WorkflowEvent::NodeReady {
            node: task_id("inspect"),
        },
    ]
    .into_iter()
    .enumerate()
    {
        store
            .append_event(
                &mut guard,
                &WorkflowEventRecord {
                    schema_version: EVENT_VERSION,
                    sequence: index as u64 + 1,
                    event,
                },
            )
            .unwrap();
    }
    drop(guard);
    std::fs::OpenOptions::new()
        .append(true)
        .open(WorkflowLayout::new(home.path()).run_events(run.manifest.run_id))
        .unwrap()
        .write_all(b"{\"schema_version\":")
        .unwrap();
    let completed = runner(home.path(), workspace.path(), Arc::new(SuccessfulExecutor))
        .drive(run.manifest.run_id, RecoveryDecision::NormalResume, None)
        .await
        .unwrap();
    assert_eq!(completed.state.state.lifecycle, RunLifecycle::Completed);
    assert_eq!(
        terminal(&completed, "inspect"),
        Some(NodeTerminalState::Success)
    );
    assert!(completed.state.last_event_sequence > 1);
    let records = store.read_events(run.manifest.run_id).unwrap();
    assert_eq!(records.last().unwrap().sequence, records.len() as u64);
}

// Covers: a prior running attempt requires explicit recovery and retains its owner.
// Owner: workflow crash recovery.
#[tokio::test]
async fn uncertain_attempt_requires_explicit_recovery() {
    let home = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let mut run = create_run(home.path(), workspace.path());
    let node = task_id("inspect");
    let attempt = AttemptNumber::new(1).unwrap();
    let store = WorkflowStore::new(home.path()).unwrap();
    let directory = WorkflowLayout::new(home.path()).run(run.manifest.run_id);
    let mut guard = store.lock_run(run.manifest.run_id).unwrap();
    for event in [
        WorkflowEvent::RunLifecycle {
            lifecycle: RunLifecycle::Running,
        },
        WorkflowEvent::NodeReady { node: node.clone() },
        WorkflowEvent::LaunchIntended {
            node: node.clone(),
            attempt,
        },
        WorkflowEvent::AttemptStarted {
            node: node.clone(),
            attempt,
            owner: ExternalOwner::Process { pid: 4242 },
        },
    ] {
        append_fixture_event(&store, &mut guard, &directory, &mut run, event);
    }
    drop(guard);
    let attempt_directory = attempt_directory(&directory, &node, attempt);
    ensure_directory_beneath(
        &directory,
        attempt_directory.strip_prefix(&directory).unwrap(),
    )
    .unwrap();
    artifacts::write_json(
        &directory,
        &attempt_directory.join("status.json"),
        &AttemptRecord {
            schema_version: ATTEMPT_VERSION,
            attempt,
            state: AttemptState::Started {
                owner: ExternalOwner::Process { pid: 4242 },
            },
        },
    )
    .unwrap();
    let error = runner(home.path(), workspace.path(), Arc::new(SuccessfulExecutor))
        .drive(run.manifest.run_id, RecoveryDecision::NormalResume, None)
        .await
        .unwrap_err();
    assert!(matches!(error, RuntimeError::NeedsRecovery { .. }));
    assert_eq!(
        store
            .load_run(run.manifest.run_id)
            .unwrap()
            .state
            .state
            .lifecycle,
        RunLifecycle::NeedsRecovery
    );
    let interrupted: AttemptRecord =
        serde_json::from_slice(&std::fs::read(attempt_directory.join("status.json")).unwrap())
            .unwrap();
    assert_eq!(
        interrupted.state,
        AttemptState::InterruptedUncertain {
            owner: ExternalOwner::Process { pid: 4242 }
        }
    );
}