supercode-harness 0.4.4

The optional native Supercode agent and tool harness
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Tests for built-in tools (P5 capability parity).

use supercode_harness::tools::{
    ApplyPatchTool, PersistentShellTool, ReadFileTool, SandboxPolicy, Tool, ToolContext,
    WriteFileTool,
};

/// Mirrors `builtins::MAX_READ_BYTES` (re-derived here since it's
/// `pub(crate)` and this is a separate integration-test crate).
const MAX_READ_BYTES: usize = 400_000;

fn ctx() -> (ToolContext, std::path::PathBuf) {
    use std::sync::atomic::{AtomicU64, Ordering};
    static N: AtomicU64 = AtomicU64::new(0);
    let dir = std::env::temp_dir().join(format!(
        "sc-tools-{}-{}",
        std::process::id(),
        N.fetch_add(1, Ordering::SeqCst)
    ));
    std::fs::create_dir_all(&dir).unwrap();
    (ToolContext::new(dir.clone()), dir)
}

#[tokio::test]
async fn apply_patch_add_update_delete_move() {
    let (ctx, dir) = ctx();
    let tool = ApplyPatchTool;

    // Seed a file to update and one to delete.
    std::fs::write(dir.join("keep.rs"), "fn main() {\n    old();\n}\n").unwrap();
    std::fs::write(dir.join("gone.txt"), "bye").unwrap();

    let patch = "\
*** Begin Patch
*** Add File: src/new.rs
+pub fn added() -> u8 {
+    42
+}
*** Update File: keep.rs
@@
 fn main() {
-    old();
+    fresh();
 }
*** Delete File: gone.txt
*** End Patch
";

    let out = tool
        .execute(serde_json::json!({ "patch": patch }), &ctx)
        .await
        .unwrap();
    assert!(out.contains("A src/new.rs"), "{out}");
    assert!(out.contains("U keep.rs"), "{out}");
    assert!(out.contains("D gone.txt"), "{out}");

    // Add wrote the new file.
    let added = std::fs::read_to_string(dir.join("src/new.rs")).unwrap();
    assert!(added.contains("pub fn added") && added.contains("42"));
    // Update replaced the hunk, preserving context.
    let updated = std::fs::read_to_string(dir.join("keep.rs")).unwrap();
    assert!(updated.contains("fresh();") && !updated.contains("old();"));
    assert!(updated.contains("fn main()"));
    // Delete removed the file.
    assert!(!dir.join("gone.txt").exists());

    // A rename via Move to.
    let mv = "\
*** Begin Patch
*** Update File: keep.rs
*** Move to: renamed.rs
@@
-    fresh();
+    fresher();
*** End Patch
";
    let out = tool
        .execute(serde_json::json!({ "patch": mv }), &ctx)
        .await
        .unwrap();
    assert!(out.contains("M keep.rs -> renamed.rs"), "{out}");
    assert!(!dir.join("keep.rs").exists());
    assert!(std::fs::read_to_string(dir.join("renamed.rs"))
        .unwrap()
        .contains("fresher();"));

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn apply_patch_reports_unmatched_hunk() {
    let (ctx, dir) = ctx();
    std::fs::write(dir.join("f.txt"), "hello world").unwrap();
    let tool = ApplyPatchTool;
    let patch = "\
*** Begin Patch
*** Update File: f.txt
@@
-not present
+replacement
*** End Patch
";
    let err = tool
        .execute(serde_json::json!({ "patch": patch }), &ctx)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("did not match"), "{err}");
    std::fs::remove_dir_all(&dir).ok();
}

// An old-block that matches more than once in the search region, with no
// `@@` anchor (or an anchor that doesn't scope to a unique region), must be
// a hard error rather than a silent edit of the first occurrence.
#[tokio::test]
async fn apply_patch_errors_on_ambiguous_hunk_without_anchor() {
    let (ctx, dir) = ctx();
    let tool = ApplyPatchTool;
    let original = "def foo():\n    return 1\n\ndef bar():\n    return 1\n";
    std::fs::write(dir.join("a.py"), original).unwrap();

    let patch = "\
*** Begin Patch
*** Update File: a.py
@@
-    return 1
+    return 2
*** End Patch
";
    let err = tool
        .execute(serde_json::json!({ "patch": patch }), &ctx)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("matches file contents"), "{err}");
    assert!(err.contains('2'), "{err}");
    assert!(
        err.contains("context") || err.contains("@@ anchor"),
        "{err}"
    );

    // Neither occurrence was edited — the file on disk is unchanged.
    let after = std::fs::read_to_string(dir.join("a.py")).unwrap();
    assert_eq!(after, original, "ambiguous hunk must not modify the file");

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn apply_patch_is_registered_as_a_builtin() {
    use supercode_harness::ToolRegistry;
    let reg = ToolRegistry::with_builtins();
    assert!(
        reg.get("apply_patch").is_some(),
        "apply_patch must be a built-in tool"
    );
    assert!(
        reg.get("shell").is_some(),
        "persistent shell must be a built-in tool"
    );
}

#[tokio::test]
async fn persistent_shell_keeps_state_across_calls() {
    let (ctx, dir) = ctx();
    let sh = PersistentShellTool::default();

    // State set in one call is visible in the next (env var + cwd persist).
    let r = sh
        .execute(serde_json::json!({"command": "MYVAR=hello123"}), &ctx)
        .await
        .unwrap();
    assert!(r.contains("exit code: 0"), "{r}");

    let r = sh
        .execute(serde_json::json!({"command": "echo $MYVAR"}), &ctx)
        .await
        .unwrap();
    assert!(r.contains("hello123"), "env var did not persist: {r}");

    // cd persists across calls — the key difference from one-shot bash.
    std::fs::create_dir_all(dir.join("sub")).unwrap();
    sh.execute(serde_json::json!({"command": "cd sub"}), &ctx)
        .await
        .unwrap();
    let r = sh
        .execute(serde_json::json!({"command": "pwd"}), &ctx)
        .await
        .unwrap();
    assert!(r.contains("/sub"), "cwd did not persist: {r}");

    // Exit code is reported.
    let r = sh
        .execute(serde_json::json!({"command": "false"}), &ctx)
        .await
        .unwrap();
    assert!(r.contains("exit code: 1"), "{r}");

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn persistent_shell_sentinel_cannot_be_spoofed() {
    let (ctx, dir) = ctx();
    let sh = PersistentShellTool::default();

    // A command that echoes the base sentinel string with a fake "0" exit code
    // must not be parsed as completion: the real exit code (7) must be
    // reported, and the echoed text must show up as ordinary output.
    let r = sh
        .execute(
            serde_json::json!({"command": "echo '__SC_SHELL_DONE__ 0'; (exit 7)"}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(
        r.contains("exit code: 7"),
        "spoofed exit code accepted: {r}"
    );
    assert!(
        r.contains("__SC_SHELL_DONE__ 0"),
        "echoed sentinel text missing from output: {r}"
    );

    // The shell must not be wedged by the echoed base string: a follow-up
    // command still completes normally with its own (per-call) sentinel.
    let r = sh
        .execute(serde_json::json!({"command": "echo still-alive"}), &ctx)
        .await
        .unwrap();
    assert!(r.contains("exit code: 0"), "{r}");
    assert!(r.contains("still-alive"), "{r}");

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn sandbox_read_only_and_workspace_write() {
    let (mut ctx, dir) = ctx();
    let w = WriteFileTool;

    // read-only: every write is denied.
    ctx.sandbox = SandboxPolicy::ReadOnly;
    let err = w
        .execute(serde_json::json!({"path": "a.txt", "content": "x"}), &ctx)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("read-only"), "{err}");
    assert!(!dir.join("a.txt").exists());

    // workspace-write: inside the workspace is allowed…
    ctx.sandbox = SandboxPolicy::WorkspaceWrite;
    w.execute(
        serde_json::json!({"path": "inside.txt", "content": "ok"}),
        &ctx,
    )
    .await
    .unwrap();
    assert_eq!(
        std::fs::read_to_string(dir.join("inside.txt")).unwrap(),
        "ok"
    );

    // …but writing outside the workspace (absolute escape or `..`) is denied.
    let outside = std::env::temp_dir().join(format!("sc-escape-{}.txt", std::process::id()));
    let err = w
        .execute(
            serde_json::json!({"path": outside.to_string_lossy(), "content": "no"}),
            &ctx,
        )
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("outside the workspace"), "{err}");
    assert!(!outside.exists());

    let err = w
        .execute(
            serde_json::json!({"path": "../escape.txt", "content": "no"}),
            &ctx,
        )
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("outside the workspace"), "{err}");

    // danger-full-access (default): writing outside is allowed.
    ctx.sandbox = SandboxPolicy::DangerFullAccess;
    w.execute(
        serde_json::json!({"path": outside.to_string_lossy(), "content": "yes"}),
        &ctx,
    )
    .await
    .unwrap();
    assert!(outside.exists());
    std::fs::remove_file(&outside).ok();

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
#[cfg(unix)]
async fn sandbox_workspace_write_rejects_a_symlink_escape() {
    // LOWER-URGENCY fix (safe-path consolidation, folded into the
    // permissions-gate CRITICAL fix): `WorkspaceWrite`'s containment check
    // (`crate::tools::path_within`) used to compare only LEXICALLY-
    // normalized paths — `..` traversal was caught, but a pre-existing
    // in-workspace symlink pointing OUTSIDE the workspace was NOT, since
    // the literal joined path (`<root>/link/passwd`) still lexically
    // "starts with" root even though it resolves elsewhere. `path_within`
    // now delegates to `crate::safe_path::contained`, which also resolves
    // symlinks along the longest existing ancestor — this proves the fix
    // through the real `WriteFileTool`/`ToolContext::check_write` path, not
    // just a unit test of the private helper.
    let (mut ctx, dir) = ctx();
    let outside = std::env::temp_dir().join(format!(
        "sc-symlink-escape-outside-{}-{}",
        std::process::id(),
        std::line!()
    ));
    std::fs::create_dir_all(&outside).unwrap();
    std::os::unix::fs::symlink(&outside, dir.join("link")).unwrap();

    ctx.sandbox = SandboxPolicy::WorkspaceWrite;
    let w = WriteFileTool;
    let err = w
        .execute(
            serde_json::json!({"path": "link/passwd", "content": "PWNED"}),
            &ctx,
        )
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("outside the workspace"), "{err}");
    assert!(
        !outside.join("passwd").exists(),
        "the write must never actually land outside the workspace root via the symlink"
    );

    std::fs::remove_dir_all(&dir).ok();
    std::fs::remove_dir_all(&outside).ok();
}

#[tokio::test]
async fn sandbox_blocks_apply_patch_writes() {
    let (mut ctx, dir) = ctx();
    ctx.sandbox = SandboxPolicy::ReadOnly;
    let tool = ApplyPatchTool;
    let patch = "*** Begin Patch\n*** Add File: blocked.rs\n+x\n*** End Patch\n";
    let err = tool
        .execute(serde_json::json!({"patch": patch}), &ctx)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("read-only"), "{err}");
    assert!(!dir.join("blocked.rs").exists());
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn persistent_shell_write_stdin() {
    let (ctx, dir) = ctx();
    let sh = PersistentShellTool::default();
    // The shell reads commands from its stdin, so raw stdin input is executed.
    let out = sh
        .execute(
            serde_json::json!({"write_stdin": "echo from_stdin_pipe\n"}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(out.contains("from_stdin_pipe"), "write_stdin output: {out}");
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn update_plan_tool() {
    use supercode_harness::tools::UpdatePlanTool;
    let (ctx, dir) = ctx();
    let tool = UpdatePlanTool::default();
    let out = tool
        .execute(
            serde_json::json!({"plan": [
                {"step": "read code", "status": "completed"},
                {"step": "fix bug", "status": "in_progress"},
                {"step": "add test"}
            ]}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(out.contains("[x] read code"));
    assert!(out.contains("[~] fix bug"));
    assert!(out.contains("[ ] add test"));
    assert_eq!(tool.current().len(), 3);
    std::fs::remove_dir_all(&dir).ok();
}

#[cfg(target_os = "macos")]
#[tokio::test]
async fn bash_os_sandbox_blocks_writes() {
    use supercode_harness::tools::BashTool;
    let (mut ctx, dir) = ctx();
    let tool = BashTool::default();

    // read-only: a subprocess write is blocked by the OS sandbox.
    ctx.sandbox = SandboxPolicy::ReadOnly;
    let out = tool
        .execute(
            serde_json::json!({"command": "echo hi > blocked.txt; echo done"}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(
        !dir.join("blocked.txt").exists(),
        "read-only sandbox must block the write: {out}"
    );

    // workspace-write: writing inside the workspace succeeds…
    ctx.sandbox = SandboxPolicy::WorkspaceWrite;
    tool.execute(serde_json::json!({"command": "echo hi > inside.txt"}), &ctx)
        .await
        .unwrap();
    assert!(
        dir.join("inside.txt").exists(),
        "workspace-write must allow writes inside cwd"
    );

    // …but writing outside the workspace is blocked.
    let outside = std::env::temp_dir().join(format!("sc-bash-escape-{}.txt", std::process::id()));
    let _ = std::fs::remove_file(&outside);
    let cmd = format!("echo hi > {}", outside.display());
    tool.execute(serde_json::json!({"command": cmd}), &ctx)
        .await
        .unwrap();
    assert!(
        !outside.exists(),
        "workspace-write must block writes outside cwd"
    );

    // full access (default): unsandboxed, the write goes through.
    ctx.sandbox = SandboxPolicy::DangerFullAccess;
    tool.execute(serde_json::json!({"command": "echo hi > free.txt"}), &ctx)
        .await
        .unwrap();
    assert!(dir.join("free.txt").exists());

    std::fs::remove_dir_all(&dir).ok();
}

// The persistent `shell` tool must honor the same OS sandbox as `bash`, or it
// becomes an unsandboxed escape hatch around the policy.
#[cfg(target_os = "macos")]
#[tokio::test]
async fn persistent_shell_os_sandbox_blocks_writes() {
    let (mut ctx, dir) = ctx();
    ctx.sandbox = SandboxPolicy::ReadOnly;
    let sh = PersistentShellTool::default();
    let out = sh
        .execute(
            serde_json::json!({"command": "echo hi > shell_blocked.txt; echo done"}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(
        !dir.join("shell_blocked.txt").exists(),
        "read-only sandbox must block the persistent shell's write: {out}"
    );
    std::fs::remove_dir_all(&dir).ok();
}

// The `@@` header anchors a hunk: it disambiguates which of several identical
// blocks to edit, and gives a pure insertion a real location.
#[tokio::test]
async fn apply_patch_at_at_anchor_disambiguates_and_locates_insertions() {
    let (ctx, dir) = ctx();
    let tool = ApplyPatchTool;
    std::fs::write(
        dir.join("a.py"),
        "def foo():\n    return 1\n\ndef bar():\n    return 1\n",
    )
    .unwrap();

    // Anchor on `bar` so the *second* `return 1` is the one changed.
    let patch = "\
*** Begin Patch
*** Update File: a.py
@@ def bar():
-    return 1
+    return 2
*** End Patch
";
    tool.execute(serde_json::json!({ "patch": patch }), &ctx)
        .await
        .unwrap();
    let after = std::fs::read_to_string(dir.join("a.py")).unwrap();
    assert_eq!(
        after, "def foo():\n    return 1\n\ndef bar():\n    return 2\n",
        "anchor must target bar, leaving foo untouched: {after:?}"
    );

    // Anchored pure insertion lands right after the anchor line, not at EOF.
    let ins = "\
*** Begin Patch
*** Update File: a.py
@@ def foo():
+    # hello
*** End Patch
";
    tool.execute(serde_json::json!({ "patch": ins }), &ctx)
        .await
        .unwrap();
    let after = std::fs::read_to_string(dir.join("a.py")).unwrap();
    assert!(
        after.starts_with("def foo():\n    # hello\n    return 1\n"),
        "insertion must follow the anchor line, not append at EOF: {after:?}"
    );

    // A missing anchor is a hard error, not a silent misapply.
    let bad = "\
*** Begin Patch
*** Update File: a.py
@@ def nope():
-    return 1
+    return 9
*** End Patch
";
    assert!(tool
        .execute(serde_json::json!({ "patch": bad }), &ctx)
        .await
        .is_err());

    std::fs::remove_dir_all(&dir).ok();
}

// ---- read_file: truncate-with-notice (SUP-14) -----------------------------

#[tokio::test]
async fn read_file_oversized_no_slice_truncates_with_notice_instead_of_erroring() {
    let (ctx, dir) = ctx();
    let tool = ReadFileTool;

    // Build a file well over MAX_READ_BYTES out of repeated numbered lines.
    let line = "the quick brown fox jumps over the lazy dog\n";
    let mut content = String::with_capacity(MAX_READ_BYTES + 50_000 + line.len());
    while content.len() < MAX_READ_BYTES + 50_000 {
        content.push_str(line);
    }
    let total = content.len();
    std::fs::write(dir.join("big.txt"), &content).unwrap();

    let out = tool
        .execute(serde_json::json!({ "path": "big.txt" }), &ctx)
        .await
        .expect("oversized read_file must succeed, not error");

    assert!(
        out.starts_with("[read_file: file is "),
        "missing truncation notice: {:?}",
        &out[..out.len().min(120)]
    );
    assert!(
        out.contains(&format!("{total} bytes")),
        "notice must state the true file size: {out}"
    );
    assert!(
        out.contains("Pass offset/limit to read more."),
        "notice must hint at offset/limit: {out}"
    );
    assert!(
        out.contains("the quick brown fox"),
        "must contain the head of the file"
    );
    // The tool-layer ceiling still bounds what's returned (notice + head).
    assert!(
        out.len() <= MAX_READ_BYTES + 200,
        "output should stay close to MAX_READ_BYTES, got {} bytes",
        out.len()
    );

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn read_file_offset_limit_still_works_on_oversized_file_with_no_notice() {
    let (ctx, dir) = ctx();
    let tool = ReadFileTool;

    let mut content = String::new();
    for i in 1..=60_000 {
        content.push_str(&format!("line {i}\n"));
    }
    assert!(
        content.len() > MAX_READ_BYTES,
        "fixture must exceed the cap"
    );
    std::fs::write(dir.join("big.txt"), &content).unwrap();

    let out = tool
        .execute(
            serde_json::json!({ "path": "big.txt", "offset": 5, "limit": 3 }),
            &ctx,
        )
        .await
        .unwrap();

    assert_eq!(out, "line 5\nline 6\nline 7");
    assert!(
        !out.contains("[read_file:"),
        "sliced reads must not carry a truncation notice: {out}"
    );

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn read_file_small_file_returns_full_content_with_no_notice() {
    let (ctx, dir) = ctx();
    let tool = ReadFileTool;

    let content = "hello\nworld\n";
    std::fs::write(dir.join("small.txt"), content).unwrap();

    let out = tool
        .execute(serde_json::json!({ "path": "small.txt" }), &ctx)
        .await
        .unwrap();

    assert_eq!(out, content, "small file must round-trip byte-for-byte");
    assert!(
        !out.contains("[read_file:"),
        "small file must not carry a truncation notice: {out}"
    );

    std::fs::remove_dir_all(&dir).ok();
}