sid-isnt-done 0.6.0

sid is a UNIX-inspired coding agent for Anthropic-compatible APIs
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
//! End-to-end tests for the ralph runner: real embedded mxsh2, the real
//! `ralph` shim on PATH, real pipes — and a scripted stub host instead of
//! LLM inference.

use std::collections::VecDeque;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, Once};

use sid_isnt_done::ralph::journal::{StepRecord, StepsJournal, SuggestionsLedger};
use sid_isnt_done::ralph::runner::{
    AgentCallResult, AgentInvocation, AgentOutcome, JudgeCallResult, JudgeInvocation, JudgeOutcome,
    RalphHost, RunnerOptions, SHIM_PATH_ENV, ScriptOutputSink, run_ralph, run_ralph_with_output,
};
use sid_isnt_done::ralph::verdict::{Finding, Severity, Verdict};
use sid_isnt_done::ralph::{EXIT_ESCALATED, EXIT_OK, EXIT_TRANSPORT};

fn ensure_shim_env() {
    static ONCE: Once = Once::new();
    ONCE.call_once(|| {
        // Safety: called exactly once before any threads depend on the value;
        // every test that reads it goes through this function first.
        unsafe {
            std::env::set_var(SHIM_PATH_ENV, env!("CARGO_BIN_EXE_ralph"));
        }
    });
}

fn temp_dir(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "sid-ralph-e2e-{name}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    fs::create_dir_all(&dir).unwrap();
    dir
}

fn options(name: &str, workspace: &Path) -> (RunnerOptions, PathBuf) {
    let run_dir = temp_dir(&format!("{name}-run"));
    (
        RunnerOptions {
            run_id: format!("{name}-run"),
            run_dir: run_dir.clone(),
            workspace_root: Some(workspace.to_path_buf()),
            max_iters: None,
            budget_tokens: None,
            resume: false,
            script_args: Vec::new(),
        },
        run_dir,
    )
}

/// A scripted host with externally visible call logs.
#[derive(Default)]
struct StubHost {
    agent_log: Arc<Mutex<Vec<AgentInvocation>>>,
    judge_log: Arc<Mutex<Vec<JudgeInvocation>>>,
    agent_results: Arc<Mutex<VecDeque<AgentCallResult>>>,
    judge_results: Arc<Mutex<VecDeque<JudgeCallResult>>>,
    /// When set, the first `fix` invocation drops a `fixed` marker file here,
    /// simulating a repair that makes `./ci` pass.
    fix_touches: Option<PathBuf>,
}

#[derive(Default)]
struct RecordingScriptOutputSink {
    chunks: Mutex<Vec<(String, Vec<u8>)>>,
}

impl RecordingScriptOutputSink {
    fn text(&self, stream: &str) -> String {
        let chunks = self.chunks.lock().unwrap();
        let bytes: Vec<u8> = chunks
            .iter()
            .filter(|(candidate, _)| candidate == stream)
            .flat_map(|(_, chunk)| chunk.iter().copied())
            .collect();
        String::from_utf8_lossy(&bytes).to_string()
    }
}

impl ScriptOutputSink for RecordingScriptOutputSink {
    fn on_script_output(&self, stream: &str, data: &[u8]) {
        self.chunks
            .lock()
            .unwrap()
            .push((stream.to_string(), data.to_vec()));
    }
}

impl RalphHost for StubHost {
    fn validate_judge(&mut self, _service: &str) -> Result<(), String> {
        Ok(())
    }

    fn run_agent(&mut self, invocation: &AgentInvocation) -> AgentCallResult {
        self.agent_log.lock().unwrap().push(invocation.clone());
        if invocation.service == "fix"
            && let Some(marker) = self.fix_touches.as_ref()
        {
            fs::write(marker, "fixed\n").unwrap();
        }
        self.agent_results
            .lock()
            .unwrap()
            .pop_front()
            .unwrap_or(AgentCallResult {
                outcome: AgentOutcome::Completed,
                tokens: 10,
                session: Some("stub".to_string()),
            })
    }

    fn judge_sample(&mut self, invocation: &JudgeInvocation) -> JudgeCallResult {
        self.judge_log.lock().unwrap().push(invocation.clone());
        self.judge_results
            .lock()
            .unwrap()
            .pop_front()
            .expect("test must script every judge sample")
    }
}

fn passing_verdict(summary: &str) -> Verdict {
    Verdict {
        sufficient: true,
        summary: summary.to_string(),
        findings: Vec::new(),
        acceptance: Vec::new(),
    }
}

fn failing_verdict(summary: &str) -> Verdict {
    Verdict {
        sufficient: false,
        summary: summary.to_string(),
        findings: vec![Finding {
            severity: Severity::Required,
            where_: "PLAN.md:1".to_string(),
            what: "Implement the missing half".to_string(),
            why: "the plan demands it".to_string(),
        }],
        acceptance: vec!["the missing half exists".to_string()],
    }
}

fn verdict_result(verdict: Verdict) -> JudgeCallResult {
    JudgeCallResult {
        outcome: JudgeOutcome::Verdict(verdict),
        tokens: 5,
    }
}

#[test]
fn inline_script_sees_run_dir_and_environment_passthrough() {
    ensure_shim_env();
    let workspace = temp_dir("inline-ws");
    let (opts, run_dir) = options("inline", &workspace);
    let report = run_ralph(
        Box::new(StubHost::default()),
        opts,
        "echo \"hello from $PLAN in $RUN_DIR\" > \"$RUN_DIR/out.txt\"",
        &[("PLAN".to_string(), "PLAN.md".to_string())],
        Arc::new(AtomicBool::new(false)),
    )
    .unwrap();
    assert_eq!(report.exit, EXIT_OK);
    let out = fs::read_to_string(run_dir.join("out.txt")).unwrap();
    assert_eq!(
        out,
        format!("hello from PLAN.md in {}\n", run_dir.display())
    );
    fs::remove_dir_all(&workspace).unwrap();
    fs::remove_dir_all(&run_dir).unwrap();
}

#[test]
fn pipes_carry_context_into_the_agent() {
    ensure_shim_env();
    let workspace = temp_dir("pipes-ws");
    let (opts, run_dir) = options("pipes", &workspace);
    let host = StubHost::default();
    let agent_log = Arc::clone(&host.agent_log);
    let report = run_ralph(
        Box::new(host),
        opts,
        "printf '%s' 'the failing log' | agent fix 'Make CI pass.'",
        &[],
        Arc::new(AtomicBool::new(false)),
    )
    .unwrap();
    assert_eq!(report.exit, EXIT_OK);
    let log = agent_log.lock().unwrap();
    assert_eq!(log.len(), 1);
    assert_eq!(log[0].service, "fix");
    assert_eq!(log[0].instruction, "Make CI pass.");
    assert_eq!(log[0].context, "the failing log");
    fs::remove_dir_all(&workspace).unwrap();
    fs::remove_dir_all(&run_dir).unwrap();
}

#[test]
fn judge_stdout_is_the_work_order_and_exit_codes_steer_the_shell() {
    ensure_shim_env();
    let workspace = temp_dir("steer-ws");
    let (opts, run_dir) = options("steer", &workspace);
    let host = StubHost::default();
    let agent_log = Arc::clone(&host.agent_log);
    host.judge_results
        .lock()
        .unwrap()
        .push_back(verdict_result(failing_verdict("not done yet")));
    // The shell pipes the rendered verdict into the task agent only on exit 1.
    let script = r#"
findings=$(judge judge "Is it done?")
case $? in
  0) echo unexpected-pass > "$RUN_DIR/path.txt" ;;
  1) printf '%s' "$findings" | agent task "Execute this work order." ;;
  *) echo unexpected-failure > "$RUN_DIR/path.txt" ;;
esac
"#;
    let report = run_ralph(
        Box::new(host),
        opts,
        script,
        &[],
        Arc::new(AtomicBool::new(false)),
    )
    .unwrap();
    assert_eq!(report.exit, EXIT_OK);
    assert!(!run_dir.join("path.txt").exists());
    let log = agent_log.lock().unwrap();
    assert_eq!(log.len(), 1);
    assert_eq!(log[0].service, "task");
    assert!(log[0].context.contains("# Verdict: insufficient"));
    assert!(log[0].context.contains("Implement the missing half"));
    fs::remove_dir_all(&workspace).unwrap();
    fs::remove_dir_all(&run_dir).unwrap();
}

#[test]
fn the_reference_ralph_script_converges() {
    ensure_shim_env();
    let workspace = temp_dir("ralph-ws");
    // A fake ./ci that fails until the `fixed` marker exists.
    let ci = workspace.join("ci");
    fs::write(
        &ci,
        "#!/bin/sh\nif test -f fixed; then echo ci ok; else echo 'ci output: not fixed'; exit 1; fi\n",
    )
    .unwrap();
    let mut perms = fs::metadata(&ci).unwrap().permissions();
    use std::os::unix::fs::PermissionsExt as _;
    perms.set_mode(0o755);
    fs::set_permissions(&ci, perms).unwrap();

    let (opts, run_dir) = options("ralph", &workspace);
    let host = StubHost {
        fix_touches: Some(workspace.join("fixed")),
        ..Default::default()
    };
    let agent_log = Arc::clone(&host.agent_log);
    let judge_log = Arc::clone(&host.judge_log);
    {
        let mut judge_results = host.judge_results.lock().unwrap();
        // First pass: a work order.  Second pass: sufficient, with a
        // suggestion that must land in the ledger and get swept.
        judge_results.push_back(verdict_result(failing_verdict("half done")));
        let mut pass = passing_verdict("The plan is complete.");
        pass.findings.push(Finding {
            severity: Severity::Suggestion,
            where_: "README.md".to_string(),
            what: "Mention the soak flag".to_string(),
            why: "operators will want it".to_string(),
        });
        judge_results.push_back(verdict_result(pass));
    }

    let script = include_str!("../init/ralph.sid");
    let report = run_ralph(
        Box::new(host),
        opts,
        script,
        &[("SOAK".to_string(), "1".to_string())],
        Arc::new(AtomicBool::new(false)),
    )
    .unwrap();

    assert_eq!(report.exit, EXIT_OK, "report: {report:?}");
    // The pre-judge CI fix is in implicit iteration 0; the two judge passes
    // are the counted fixpoint iterations.
    assert_eq!(report.iterations, 2);
    assert_eq!(
        report.agent_counts,
        vec![("fix".to_string(), 1), ("task".to_string(), 2)]
    );
    assert_eq!(
        report.final_verdict_summary.as_deref(),
        Some("The plan is complete.")
    );
    assert_eq!(report.final_soak, Some((1, 1)));
    assert_eq!(report.suggestions_entries, 1);

    let log = agent_log.lock().unwrap();
    // The fix agent got the piped CI log.
    assert_eq!(log[0].service, "fix");
    assert!(log[0].context.contains("ci output: not fixed"));
    // The task agent got the rendered work order.
    assert_eq!(log[1].service, "task");
    assert!(log[1].context.contains("Implement the missing half"));
    // The sweep got the suggestions ledger on stdin.
    assert_eq!(log[2].service, "task");
    assert!(log[2].context.contains("Mention the soak flag"));

    // The judge's prompts: both passes mention the plan; the second pass is
    // mid-soak with the previous prompt's soak framing.
    let judges = judge_log.lock().unwrap();
    assert_eq!(judges.len(), 2);
    assert!(judges[0].prompt.contains("Is PLAN.md complete"));
    assert!(judges[0].prompt.contains("soak pass 1 of 1"));

    // The journal narrates the whole run.
    let records = StepsJournal::new(&run_dir).load().unwrap();
    let kinds: Vec<&str> = records
        .iter()
        .map(|record| match record {
            StepRecord::RunStart { .. } => "start",
            StepRecord::Agent { .. } => "agent",
            StepRecord::Judge { .. } => "judge",
        })
        .collect();
    assert_eq!(
        kinds,
        vec!["start", "agent", "judge", "agent", "judge", "agent"]
    );
    assert!(
        SuggestionsLedger::new(&run_dir)
            .read()
            .contains("Mention the soak flag")
    );

    fs::remove_dir_all(&workspace).unwrap();
    fs::remove_dir_all(&run_dir).unwrap();
}

#[test]
fn the_reference_ralph_script_streams_ci_output() {
    ensure_shim_env();
    let workspace = temp_dir("ralph-stream-ws");
    let ci = workspace.join("ci");
    fs::write(
        &ci,
        "#!/bin/sh\n\
echo 'ci stdout: start'\n\
echo 'ci stderr: checking' >&2\n\
if test -f fixed; then echo 'ci stdout: ok'; else echo 'ci output: not fixed'; exit 1; fi\n",
    )
    .unwrap();
    let mut perms = fs::metadata(&ci).unwrap().permissions();
    use std::os::unix::fs::PermissionsExt as _;
    perms.set_mode(0o755);
    fs::set_permissions(&ci, perms).unwrap();

    let (opts, run_dir) = options("ralph-stream", &workspace);
    let host = StubHost {
        fix_touches: Some(workspace.join("fixed")),
        ..Default::default()
    };
    host.judge_results
        .lock()
        .unwrap()
        .push_back(verdict_result(passing_verdict("The plan is complete.")));
    let agent_log = Arc::clone(&host.agent_log);
    let sink = Arc::new(RecordingScriptOutputSink::default());
    let output_sink: Arc<dyn ScriptOutputSink> = sink.clone();

    let script = include_str!("../init/ralph.sid");
    let report = run_ralph_with_output(
        Box::new(host),
        opts,
        script,
        &[("SOAK".to_string(), "1".to_string())],
        Arc::new(AtomicBool::new(false)),
        Some(output_sink),
    )
    .unwrap();

    assert_eq!(report.exit, EXIT_OK, "report: {report:?}");
    let streamed = sink.text("stdout");
    assert!(streamed.contains("ci stdout: start"));
    assert!(streamed.contains("ci stderr: checking"));
    assert!(streamed.contains("ci output: not fixed"));
    assert!(streamed.contains("ci stdout: ok"));

    let log = agent_log.lock().unwrap();
    assert_eq!(log[0].service, "fix");
    assert!(log[0].context.contains("ci stdout: start"));
    assert!(log[0].context.contains("ci stderr: checking"));
    assert!(log[0].context.contains("ci output: not fixed"));

    fs::remove_dir_all(&workspace).unwrap();
    fs::remove_dir_all(&run_dir).unwrap();
}

#[test]
fn escalation_stops_the_reference_loop_with_exit_three() {
    ensure_shim_env();
    let workspace = temp_dir("escalate-ws");
    let ci = workspace.join("ci");
    fs::write(&ci, "#!/bin/sh\nexit 1\n").unwrap();
    let mut perms = fs::metadata(&ci).unwrap().permissions();
    use std::os::unix::fs::PermissionsExt as _;
    perms.set_mode(0o755);
    fs::set_permissions(&ci, perms).unwrap();

    let (opts, run_dir) = options("escalate", &workspace);
    let host = StubHost::default();
    host.agent_results
        .lock()
        .unwrap()
        .push_back(AgentCallResult {
            outcome: AgentOutcome::Escalated("ci needs credentials".to_string()),
            tokens: 1,
            session: None,
        });
    let script = include_str!("../init/ralph.sid");
    let report = run_ralph(
        Box::new(host),
        opts,
        script,
        &[],
        Arc::new(AtomicBool::new(false)),
    )
    .unwrap();
    assert_eq!(report.exit, EXIT_ESCALATED);
    fs::remove_dir_all(&workspace).unwrap();
    fs::remove_dir_all(&run_dir).unwrap();
}

#[test]
fn max_iters_does_not_charge_implicit_zero_iteration_agents() {
    ensure_shim_env();
    let workspace = temp_dir("iters-ws");
    let (mut opts, run_dir) = options("iters", &workspace);
    opts.max_iters = Some(2);
    let host = StubHost::default();
    let script = r#"
agent fix || exit $?
agent fix || exit $?
agent fix || exit $?
exit 0
"#;
    let report = run_ralph(
        Box::new(host),
        opts,
        script,
        &[],
        Arc::new(AtomicBool::new(false)),
    )
    .unwrap();
    assert_eq!(report.exit, EXIT_OK);
    assert_eq!(report.iterations, 0);
    assert_eq!(report.agent_counts, vec![("fix".to_string(), 3)]);
    fs::remove_dir_all(&workspace).unwrap();
    fs::remove_dir_all(&run_dir).unwrap();
}

#[test]
fn max_iters_stops_between_judge_started_iterations() {
    ensure_shim_env();
    let workspace = temp_dir("judge-iters-ws");
    let (mut opts, run_dir) = options("judge-iters", &workspace);
    opts.max_iters = Some(1);
    let host = StubHost::default();
    let agent_log = Arc::clone(&host.agent_log);
    let judge_log = Arc::clone(&host.judge_log);
    host.judge_results
        .lock()
        .unwrap()
        .push_back(verdict_result(failing_verdict("needs work")));

    let script = r#"
findings=$(judge judge "first pass")
case $? in
  1)
    printf '%s' "$findings" | agent task "Execute this work order."
    agent task '$commit'
    ;;
  *) exit $? ;;
esac
judge judge "second pass"
exit $?
"#;
    let report = run_ralph(
        Box::new(host),
        opts,
        script,
        &[],
        Arc::new(AtomicBool::new(false)),
    )
    .unwrap();
    assert_eq!(report.exit, EXIT_TRANSPORT);
    assert_eq!(report.iterations, 1);
    assert_eq!(report.agent_counts, vec![("task".to_string(), 2)]);
    assert_eq!(agent_log.lock().unwrap().len(), 2);
    assert_eq!(judge_log.lock().unwrap().len(), 1);
    fs::remove_dir_all(&workspace).unwrap();
    fs::remove_dir_all(&run_dir).unwrap();
}

#[test]
fn debug_sweep_snippet() {
    ensure_shim_env();
    let workspace = temp_dir("dbg-ws");
    let (opts, run_dir) = options("dbg", &workspace);
    fs::write(run_dir.join("suggestions.md"), "- a suggestion\n").unwrap();
    let host = StubHost::default();
    let agent_log = Arc::clone(&host.agent_log);
    let script = r#"
test -s "$RUN_DIR/suggestions.md" &&
  agent task "Triage:" < "$RUN_DIR/suggestions.md"

exit 0
"#;
    let report = run_ralph(
        Box::new(host),
        opts,
        script,
        &[],
        Arc::new(AtomicBool::new(false)),
    )
    .unwrap();
    eprintln!("report: {report:?}");
    eprintln!("agents: {:?}", agent_log.lock().unwrap().len());
    assert_eq!(report.exit, EXIT_OK);
    assert_eq!(agent_log.lock().unwrap().len(), 1);
    fs::remove_dir_all(&workspace).unwrap();
    fs::remove_dir_all(&run_dir).unwrap();
}