supercode-harness 0.4.8

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
//! P4b (COMPOSABLE-HARNESS-DESIGN.md §5.2 "P4", §1.4 obligation 4 assembly
//! site): env-context block, global/user instruction tier, and
//! instruction-walk nuances (`@path` imports + `project_doc_max_bytes`).
//! Drives `Agent::with_parts` (via `Agent::with_provider`, which never needs
//! a real API key/network) and inspects the resulting system message
//! (`agent.history()[0]`).

use async_trait::async_trait;
use supercode_harness::{Agent, ChatMessage, ChatRequest, Config, Provider, Usage};

/// A provider that's never actually called — these tests only inspect the
/// system prompt `Agent::with_parts` assembles at construction time.
struct NeverCalled;
#[async_trait]
impl Provider for NeverCalled {
    async fn complete(
        &self,
        _req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode_harness::Result<(ChatMessage, Usage)> {
        panic!("provider should never be called by these assembly-only tests");
    }
}

fn system_prompt_of(config: Config) -> String {
    let agent = Agent::with_provider(config, Box::new(NeverCalled));
    agent.history()[0].content.clone().unwrap_or_default()
}

fn temp_dir(tag: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "supercode-p4b-instr-{tag}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

/// Serializes any test that mutates the process-wide `SUPERCODE_HOME` env
/// var — mirrors `crates/cli/src/main.rs::tests::lock_supercode_home_env`'s
/// exact rationale: `cargo test` runs test functions across threads by
/// default, and an unguarded `std::env::set_var` is shared process state.
fn lock_supercode_home_env() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    LOCK.lock().unwrap_or_else(|e| e.into_inner())
}

// ============================ global instruction tier ======================

#[test]
fn global_instruction_tier_is_loaded_when_project_context_is_on() {
    let _guard = lock_supercode_home_env();
    let global_home = temp_dir("global-home");
    std::fs::write(global_home.join("AGENTS.md"), "GLOBAL MARKER TEXT").unwrap();
    let cwd = temp_dir("global-cwd-empty");
    std::env::set_var("SUPERCODE_HOME", &global_home);

    let config = Config::builder().cwd(&cwd).project_context(true).build();
    let system = system_prompt_of(config);
    std::env::remove_var("SUPERCODE_HOME");

    assert!(
        system.contains("GLOBAL MARKER TEXT"),
        "global tier must load when project_context is on: {system}"
    );

    let _ = std::fs::remove_dir_all(&global_home);
    let _ = std::fs::remove_dir_all(&cwd);
}

#[test]
fn global_instruction_tier_is_not_loaded_when_project_context_is_off() {
    let _guard = lock_supercode_home_env();
    let global_home = temp_dir("global-home-off");
    std::fs::write(
        global_home.join("AGENTS.md"),
        "GLOBAL MARKER SHOULD NOT APPEAR",
    )
    .unwrap();
    let cwd = temp_dir("global-cwd-off");
    std::env::set_var("SUPERCODE_HOME", &global_home);

    let config = Config::builder().cwd(&cwd).project_context(false).build();
    let system = system_prompt_of(config);
    std::env::remove_var("SUPERCODE_HOME");

    assert!(
        !system.contains("GLOBAL MARKER SHOULD NOT APPEAR"),
        "project_context = false (the default) must be byte-identical to pre-P4b behavior"
    );

    let _ = std::fs::remove_dir_all(&global_home);
    let _ = std::fs::remove_dir_all(&cwd);
}

#[test]
fn cwd_tier_still_loads_project_context_unchanged_from_pre_p4b() {
    let cwd = temp_dir("cwd-project-unchanged");
    std::fs::write(cwd.join("CLAUDE.md"), "PROJECT MARKER TEXT").unwrap();
    let config = Config::builder().cwd(&cwd).project_context(true).build();
    let system = system_prompt_of(config);
    assert!(system.contains("PROJECT MARKER TEXT"));
    let _ = std::fs::remove_dir_all(&cwd);
}

#[test]
fn nearer_to_cwd_instruction_content_appears_after_the_global_tier() {
    let _guard = lock_supercode_home_env();
    let global_home = temp_dir("order-global");
    std::fs::write(global_home.join("AGENTS.md"), "GLOBAL-ORDER-MARKER").unwrap();
    let cwd = temp_dir("order-cwd");
    std::fs::write(cwd.join("AGENTS.md"), "PROJECT-ORDER-MARKER").unwrap();
    std::env::set_var("SUPERCODE_HOME", &global_home);

    let config = Config::builder().cwd(&cwd).project_context(true).build();
    let system = system_prompt_of(config);
    std::env::remove_var("SUPERCODE_HOME");

    let global_pos = system
        .find("GLOBAL-ORDER-MARKER")
        .expect("global tier present");
    let project_pos = system
        .find("PROJECT-ORDER-MARKER")
        .expect("project tier present");
    assert!(
        global_pos < project_pos,
        "root-first ordering: global tier must appear BEFORE the project tier (nearer-to-cwd wins by appearing later)"
    );

    let _ = std::fs::remove_dir_all(&global_home);
    let _ = std::fs::remove_dir_all(&cwd);
}

// ============================== env-context block ==========================

#[test]
fn env_context_block_appended_when_enabled() {
    let cwd = temp_dir("env-ctx-on");
    let config = Config::builder().cwd(&cwd).env_context(true).build();
    let system = system_prompt_of(config);
    assert!(system.contains("# Environment"), "{system}");
    assert!(system.contains("cwd:"), "{system}");
    assert!(system.contains("platform:"), "{system}");
    assert!(system.contains("date:"), "{system}");
    let _ = std::fs::remove_dir_all(&cwd);
}

#[test]
fn env_context_block_absent_by_default() {
    let cwd = temp_dir("env-ctx-off");
    let config = Config::builder().cwd(&cwd).build();
    let system = system_prompt_of(config);
    assert!(!system.contains("# Environment"), "{system}");
    let _ = std::fs::remove_dir_all(&cwd);
}

// ============================ instruction imports ===========================

#[test]
fn instruction_imports_inlines_the_referenced_file_content() {
    let cwd = temp_dir("imports-on");
    std::fs::write(cwd.join("STYLE.md"), "Use tabs, not spaces.").unwrap();
    std::fs::write(
        cwd.join("AGENTS.md"),
        "Follow the style guide: @STYLE.md please.",
    )
    .unwrap();
    let config = Config::builder()
        .cwd(&cwd)
        .project_context(true)
        .instruction_imports(true)
        .build();
    let system = system_prompt_of(config);
    assert!(
        system.contains("Use tabs, not spaces."),
        "the imported file's content must be inlined: {system}"
    );
    assert!(
        !system.contains("@STYLE.md"),
        "the literal @STYLE.md token must have been replaced: {system}"
    );
    let _ = std::fs::remove_dir_all(&cwd);
}

#[test]
fn instruction_imports_off_by_default_leaves_the_at_token_literal() {
    let cwd = temp_dir("imports-off");
    std::fs::write(cwd.join("STYLE.md"), "Use tabs, not spaces.").unwrap();
    std::fs::write(
        cwd.join("AGENTS.md"),
        "Follow the style guide: @STYLE.md please.",
    )
    .unwrap();
    let config = Config::builder().cwd(&cwd).project_context(true).build();
    let system = system_prompt_of(config);
    assert!(
        system.contains("@STYLE.md"),
        "instruction_imports defaults off: the token must stay literal: {system}"
    );
    assert!(!system.contains("Use tabs, not spaces."));
    let _ = std::fs::remove_dir_all(&cwd);
}

#[test]
fn instruction_imports_reject_path_traversal_from_a_project_sourced_file() {
    let cwd = temp_dir("imports-traversal");
    // A secret OUTSIDE the project root (a sibling of `cwd` under the same
    // temp-dir parent) that a malicious repo's AGENTS.md must never be able
    // to pull into the system prompt via `@..` traversal.
    let secret_parent = temp_dir("imports-traversal-secret-parent");
    std::fs::write(secret_parent.join("SECRET.md"), "TOP SECRET CONTENT").unwrap();
    let secret_name = secret_parent.file_name().unwrap().to_str().unwrap();
    std::fs::write(
        cwd.join("AGENTS.md"),
        format!("@../{secret_name}/SECRET.md"),
    )
    .unwrap();
    let config = Config::builder()
        .cwd(&cwd)
        .project_context(true)
        .instruction_imports(true)
        .build();
    let system = system_prompt_of(config);
    assert!(
        !system.contains("TOP SECRET CONTENT"),
        "a `..`-traversing import from a PROJECT-sourced file must be rejected: {system}"
    );
    let _ = std::fs::remove_dir_all(&cwd);
    let _ = std::fs::remove_dir_all(&secret_parent);
}

#[test]
fn instruction_imports_absolute_path_from_a_project_sourced_file_is_rejected() {
    let cwd = temp_dir("imports-absolute");
    let secret = temp_dir("imports-absolute-secret");
    let secret_file = secret.join("SECRET.md");
    std::fs::write(&secret_file, "ABSOLUTE SECRET").unwrap();
    std::fs::write(cwd.join("AGENTS.md"), format!("@{}", secret_file.display())).unwrap();
    let config = Config::builder()
        .cwd(&cwd)
        .project_context(true)
        .instruction_imports(true)
        .build();
    let system = system_prompt_of(config);
    assert!(!system.contains("ABSOLUTE SECRET"), "{system}");
    let _ = std::fs::remove_dir_all(&cwd);
    let _ = std::fs::remove_dir_all(&secret);
}

// ================= instruction imports: symlink containment ================
// P4b security fix (Fable-5 review, MEDIUM): `import_path_is_safe`'s lexical
// check (no `..`, no absolute, no `~`) rejects the two named attacks above
// but not a symlink committed IN the repo whose own relative name is clean
// while its resolved TARGET escapes the root. These tests exercise the
// canonicalize-and-contain fix (`import_target_is_contained` in agent.rs).

#[cfg(unix)]
#[test]
fn instruction_imports_symlink_escaping_the_project_root_is_rejected() {
    let cwd = temp_dir("imports-symlink-escape");
    let secret_parent = temp_dir("imports-symlink-escape-secret-parent");
    let secret_file = secret_parent.join("SECRET.md");
    std::fs::write(&secret_file, "SYMLINK ESCAPE SECRET").unwrap();
    // `link.md` lives INSIDE the repo and has a perfectly clean relative
    // name, but resolves to a file OUTSIDE the project root — the exact
    // review repro.
    std::os::unix::fs::symlink(&secret_file, cwd.join("link.md")).unwrap();
    std::fs::write(cwd.join("AGENTS.md"), "@link.md").unwrap();
    let config = Config::builder()
        .cwd(&cwd)
        .project_context(true)
        .instruction_imports(true)
        .build();
    let system = system_prompt_of(config);
    assert!(
        !system.contains("SYMLINK ESCAPE SECRET"),
        "a symlink committed in-repo whose TARGET escapes the root must be rejected: {system}"
    );
    let _ = std::fs::remove_dir_all(&cwd);
    let _ = std::fs::remove_dir_all(&secret_parent);
}

#[test]
fn instruction_imports_in_root_subdirectory_file_is_still_inlined() {
    // No symlink at all — guards against the containment fix over-rejecting
    // a genuinely-in-root file reached via a subdirectory.
    let cwd = temp_dir("imports-in-root-subdir");
    std::fs::create_dir_all(cwd.join("sub")).unwrap();
    std::fs::write(cwd.join("sub").join("real.md"), "IN ROOT SUBDIR CONTENT").unwrap();
    std::fs::write(cwd.join("AGENTS.md"), "@sub/real.md").unwrap();
    let config = Config::builder()
        .cwd(&cwd)
        .project_context(true)
        .instruction_imports(true)
        .build();
    let system = system_prompt_of(config);
    assert!(
        system.contains("IN ROOT SUBDIR CONTENT"),
        "a genuinely in-root file must not be falsely rejected by the containment check: {system}"
    );
    let _ = std::fs::remove_dir_all(&cwd);
}

#[cfg(unix)]
#[test]
fn instruction_imports_symlink_pointing_within_the_project_root_is_inlined() {
    // A symlink is fine as long as its resolved target is ALSO inside the
    // root — only escapes must be rejected.
    let cwd = temp_dir("imports-symlink-in-root");
    std::fs::write(cwd.join("real.md"), "IN ROOT SYMLINK TARGET").unwrap();
    std::os::unix::fs::symlink(cwd.join("real.md"), cwd.join("link.md")).unwrap();
    std::fs::write(cwd.join("AGENTS.md"), "@link.md").unwrap();
    let config = Config::builder()
        .cwd(&cwd)
        .project_context(true)
        .instruction_imports(true)
        .build();
    let system = system_prompt_of(config);
    assert!(
        system.contains("IN ROOT SYMLINK TARGET"),
        "an in-root symlink (target also under the project root) must still be inlined: {system}"
    );
    let _ = std::fs::remove_dir_all(&cwd);
}

#[cfg(unix)]
#[test]
fn instruction_imports_broken_symlink_is_rejected_without_panicking() {
    let cwd = temp_dir("imports-broken-symlink");
    std::os::unix::fs::symlink(cwd.join("does-not-exist.md"), cwd.join("link.md")).unwrap();
    std::fs::write(cwd.join("AGENTS.md"), "@link.md").unwrap();
    let config = Config::builder()
        .cwd(&cwd)
        .project_context(true)
        .instruction_imports(true)
        .build();
    // Must not panic (canonicalize() fails on a broken symlink target) and
    // must fail closed: the literal `@link.md` token is left untouched
    // rather than the loop crashing or silently inlining nothing useful.
    let system = system_prompt_of(config);
    assert!(system.contains("@link.md"), "{system}");
    let _ = std::fs::remove_dir_all(&cwd);
}

#[cfg(unix)]
#[test]
fn instruction_imports_global_tier_symlink_stays_unrestricted() {
    // The global/user tier is trusted (same level as the user's own shell)
    // and must NOT be run through the project-scoped containment check —
    // guard against the fix over-restricting the trusted tier.
    let _guard = lock_supercode_home_env();
    let global_home = temp_dir("imports-global-symlink-home");
    let outside = temp_dir("imports-global-symlink-target");
    std::fs::write(outside.join("OUTSIDE.md"), "GLOBAL TRUSTED TARGET").unwrap();
    std::os::unix::fs::symlink(outside.join("OUTSIDE.md"), global_home.join("link.md")).unwrap();
    std::fs::write(global_home.join("AGENTS.md"), "@link.md").unwrap();
    let cwd = temp_dir("imports-global-symlink-cwd");
    std::env::set_var("SUPERCODE_HOME", &global_home);

    let config = Config::builder()
        .cwd(&cwd)
        .project_context(true)
        .instruction_imports(true)
        .build();
    let system = system_prompt_of(config);
    std::env::remove_var("SUPERCODE_HOME");

    assert!(
        system.contains("GLOBAL TRUSTED TARGET"),
        "global/user-tier imports are trusted and must stay unrestricted: {system}"
    );

    let _ = std::fs::remove_dir_all(&global_home);
    let _ = std::fs::remove_dir_all(&outside);
    let _ = std::fs::remove_dir_all(&cwd);
}

// =========================== project_doc_max_bytes ==========================

#[test]
fn project_doc_max_bytes_caps_the_total_assembled_instruction_content() {
    let cwd = temp_dir("max-bytes-on");
    let huge = "x".repeat(50_000);
    std::fs::write(cwd.join("CLAUDE.md"), &huge).unwrap();
    let config = Config::builder()
        .cwd(&cwd)
        .project_context(true)
        .project_doc_max_bytes(200)
        .build();
    let system = system_prompt_of(config);
    // The base system prompt itself plus the notice is small; the huge
    // instruction body must not have made it through uncapped.
    assert!(
        system.len() < huge.len(),
        "assembled system prompt ({} bytes) must be far smaller than the uncapped instruction file ({} bytes)",
        system.len(),
        huge.len()
    );
    assert!(
        system.contains("truncated at core.project_doc_max_bytes"),
        "{system}"
    );
    let _ = std::fs::remove_dir_all(&cwd);
}

#[test]
fn project_doc_max_bytes_unset_leaves_instruction_content_uncapped() {
    let cwd = temp_dir("max-bytes-off");
    let body = "y".repeat(5_000);
    std::fs::write(cwd.join("CLAUDE.md"), &body).unwrap();
    let config = Config::builder().cwd(&cwd).project_context(true).build();
    let system = system_prompt_of(config);
    assert!(system.contains(&body), "uncapped by default");
    assert!(!system.contains("truncated at core.project_doc_max_bytes"));
    let _ = std::fs::remove_dir_all(&cwd);
}