supercode-harness 0.4.21

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
//! ORCH-21 dev/01 — the controlled tier over `harness.v1.profiles.*`,
//! exercised against FAKE harness CLIs.
//!
//! Each fake records its argv (one argument per line) and makes the change the
//! real harness would make to its OWN store — a directory under
//! `HERMES_HOME/profiles/`, an entry in `agents.list` — so what is under test
//! is exactly supercode's half of the contract:
//!
//! * the uniform row is translated onto the HARNESS'S OWN verb
//!   (`hermes profile create|delete`, `openclaw agents add|delete`),
//! * the answer is RE-READ through the ORCH-10 loader afterwards, never echoed
//!   from the request,
//! * a failing verb surfaces the harness's own stderr, and
//! * a harness whose profiles are file-authored (Codex) or compiled in
//!   (supercode presets) refuses with `unsupported_action`.
//!
//! No real harness, no gateway, no network, no model spend. This file owns its
//! own process, so the `SUPERCODE_*_BIN` overrides cannot race another test.

use std::path::{Path, PathBuf};

use serde_json::{json, Value};
use supercode_harness::harness_service::HARNESS_SERVICE_METHODS;
use supercode_harness::jobs_control::{HERMES_BIN_ENV, OPENCLAW_BIN_ENV};
use supercode_harness::{HarnessSessionService, SdkOperation};

/// `SUPERCODE_*_BIN` is process-global, so the tests that set it run one at a
/// time even though cargo runs the file's tests in threads.
static BIN_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

fn bin_lock() -> std::sync::MutexGuard<'static, ()> {
    BIN_LOCK.lock().unwrap_or_else(|error| error.into_inner())
}

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

fn request(method: &str, params: Value) -> Value {
    json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
}

fn call(service: &mut HarnessSessionService, method: &str, params: Value) -> Value {
    let response = service.handle(request(method, params));
    assert!(response.get("error").is_none(), "{method}: {response}");
    response["result"].clone()
}

fn make_executable(path: &Path) {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    #[cfg(not(unix))]
    let _ = path;
}

/// A fake `hermes` that makes and removes the profile HOME its own verb makes
/// and removes, under the `HERMES_HOME` it was handed.
fn write_fake_hermes(root: &Path) -> PathBuf {
    let path = root.join("fake-hermes");
    std::fs::write(
        &path,
        "#!/bin/sh\n\
         dir=$(dirname \"$0\")\n\
         for a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$dir/hermes.argv\"; name=$a; done\n\
         case \"$*\" in *missing*) printf \"Profile 'missing' does not exist.\\n\" >&2; exit 1 ;; esac\n\
         case \"$2\" in\n\
         create) mkdir -p \"$HERMES_HOME/profiles/$name\" ;;\n\
         delete) rm -rf \"$HERMES_HOME/profiles/$name\" ;;\n\
         esac\n\
         printf 'ok\\n'\n",
    )
    .unwrap();
    make_executable(&path);
    path
}

/// A fake `openclaw` that copies `openclaw.<verb>.json` over the state dir's
/// `openclaw.json` — the file its own `agents add|delete` edits at the pin.
fn write_fake_openclaw(root: &Path) -> PathBuf {
    let path = root.join("fake-openclaw");
    std::fs::write(
        &path,
        "#!/bin/sh\n\
         dir=$(dirname \"$0\")\n\
         for a in \"$@\"; do printf '%s\\n' \"$a\" >> \"$dir/openclaw.argv\"; done\n\
         case \"$*\" in *missing*) printf 'Agent \"missing\" not found.\\n' >&2; exit 1 ;; esac\n\
         verb=$2\n\
         if [ -f \"$dir/openclaw.$verb.json\" ]; then\n\
         cp \"$dir/openclaw.$verb.json\" \"$OPENCLAW_STATE_DIR/openclaw.json\"\n\
         fi\n\
         printf 'ok\\n'\n",
    )
    .unwrap();
    make_executable(&path);
    path
}

fn write_config(path: &Path, value: Value) {
    std::fs::write(path, serde_json::to_string(&value).unwrap()).unwrap();
}

fn argv_log(root: &Path, harness: &str) -> String {
    std::fs::read_to_string(root.join(format!("{harness}.argv"))).unwrap_or_default()
}

/// The narration with the (temp-path) program stripped, so an assertion can
/// name the verb the harness ran.
fn ran_arguments(result: &Value) -> String {
    let ran = result["ran"]
        .as_str()
        .expect("every outcome narrates `ran`");
    ran.split_once(' ')
        .map(|(_, rest)| rest.to_string())
        .unwrap_or_default()
}

fn profile_names(listing: &Value) -> Vec<String> {
    listing["profiles"]
        .as_array()
        .expect("a profiles array")
        .iter()
        .map(|row| row["name"].as_str().unwrap_or_default().to_string())
        .collect()
}

#[test]
fn hermes_profiles_are_made_and_removed_by_hermess_own_verb() {
    let _guard = bin_lock();
    let root = scratch_dir("hermes");
    let home = root.join("hermes_home");
    std::fs::create_dir_all(&home).unwrap();
    let cli = write_fake_hermes(&root);
    std::env::set_var(HERMES_BIN_ENV, &cli);
    let homes = json!({"hermes": home.join("state.db")});
    let mut service = HarnessSessionService::new();

    let created = call(
        &mut service,
        "harness.v1.profiles.create",
        json!({
            "harness": "hermes",
            "name": "coder",
            "from": "default",
            "homes": homes,
        }),
    );
    // `--no-alias`: the wrapper script would land in `~/.local/bin`, outside
    // the home the caller addressed.
    assert_eq!(
        ran_arguments(&created),
        "profile create --clone-from default --no-alias coder"
    );
    assert_eq!(created["name"], "coder", "{created}");
    assert_eq!(created["profile"]["kind"], "hermes_profile");
    assert_eq!(created["profile"]["default"], false);
    assert!(created["profile"]["home"]
        .as_str()
        .unwrap_or_default()
        .ends_with("hermes_home/profiles/coder"));
    // HERMES_HOME reached the child: the home it made is under the isolated
    // root, not under the real one.
    assert!(home.join("profiles/coder").is_dir());
    // The argv the harness actually received, not just the narration.
    let log = argv_log(&root, "hermes");
    assert!(
        log.contains("\ncreate\n") && log.contains("\n--no-alias\n"),
        "{log}"
    );

    // The read side agrees: the ORCH-10 listing now holds the new profile.
    let listing = call(
        &mut service,
        "harness.v1.profiles.list",
        json!({"harness": "hermes", "homes": homes}),
    );
    assert!(
        profile_names(&listing).contains(&"coder".to_string()),
        "{listing}"
    );

    let deleted = call(
        &mut service,
        "harness.v1.profiles.delete",
        json!({"harness": "hermes", "name": "coder", "homes": homes}),
    );
    assert_eq!(ran_arguments(&deleted), "profile delete --yes coder");
    assert_eq!(deleted["deleted"], true, "{deleted}");
    assert!(deleted.get("profile").is_none(), "{deleted}");
    // The delete is confirmed against the harness's own store, not the exit
    // code: the home is gone and the listing no longer reports it.
    assert!(!home.join("profiles/coder").exists());
    let listing = call(
        &mut service,
        "harness.v1.profiles.list",
        json!({"harness": "hermes", "homes": homes}),
    );
    assert_eq!(
        profile_names(&listing),
        vec!["default".to_string()],
        "{listing}"
    );

    std::env::remove_var(HERMES_BIN_ENV);
    std::fs::remove_dir_all(&root).ok();
}

#[test]
fn openclaw_agents_are_added_and_deleted_by_openclaws_own_verb() {
    let _guard = bin_lock();
    let root = scratch_dir("openclaw");
    let home = root.join("openclaw_home");
    std::fs::create_dir_all(&home).unwrap();
    let workspace = root.join("ws");
    write_config(
        &home.join("openclaw.json"),
        json!({"agents": {"list": [{"id": "main"}]}}),
    );
    let cli = write_fake_openclaw(&root);
    write_config(
        &root.join("openclaw.add.json"),
        json!({"agents": {"list": [
            {"id": "main"},
            {"id": "ops", "workspace": workspace, "model": "mock/mock-model"},
        ]}}),
    );
    write_config(
        &root.join("openclaw.delete.json"),
        json!({"agents": {"list": [{"id": "main"}]}}),
    );
    std::env::set_var(OPENCLAW_BIN_ENV, &cli);
    let homes = json!({"openclaw": home});
    let mut service = HarnessSessionService::new();

    let created = call(
        &mut service,
        "harness.v1.profiles.create",
        json!({
            "harness": "openclaw",
            "name": "ops",
            "workspace": workspace,
            "homes": homes,
        }),
    );
    assert_eq!(
        ran_arguments(&created),
        format!(
            "agents add ops --workspace {} --non-interactive --json",
            workspace.display()
        )
    );
    assert_eq!(created["name"], "ops", "{created}");
    assert_eq!(created["profile"]["kind"], "openclaw_agent");
    assert_eq!(created["profile"]["model"], "mock/mock-model");
    let log = argv_log(&root, "openclaw");
    assert!(
        log.contains("\nadd\n") && log.contains("\n--non-interactive\n"),
        "{log}"
    );

    let listing = call(
        &mut service,
        "harness.v1.profiles.list",
        json!({"harness": "openclaw", "homes": homes}),
    );
    assert!(
        profile_names(&listing).contains(&"ops".to_string()),
        "{listing}"
    );

    let deleted = call(
        &mut service,
        "harness.v1.profiles.delete",
        json!({"harness": "openclaw", "name": "ops", "homes": homes}),
    );
    assert_eq!(ran_arguments(&deleted), "agents delete ops --force --json");
    assert_eq!(deleted["deleted"], true, "{deleted}");
    let listing = call(
        &mut service,
        "harness.v1.profiles.list",
        json!({"harness": "openclaw", "homes": homes}),
    );
    assert_eq!(
        profile_names(&listing),
        vec!["main".to_string()],
        "{listing}"
    );

    std::env::remove_var(OPENCLAW_BIN_ENV);
    std::fs::remove_dir_all(&root).ok();
}

#[test]
fn openclaw_create_needs_the_workspace_its_own_verb_demands() {
    let _guard = bin_lock();
    let root = scratch_dir("workspace");
    let home = root.join("openclaw_home");
    std::fs::create_dir_all(&home).unwrap();
    write_config(
        &home.join("openclaw.json"),
        json!({"agents": {"list": [{"id": "main"}]}}),
    );
    let cli = write_fake_openclaw(&root);
    std::env::set_var(OPENCLAW_BIN_ENV, &cli);
    let mut service = HarnessSessionService::new();
    let response = service.handle(request(
        "harness.v1.profiles.create",
        json!({"harness": "openclaw", "name": "ops", "homes": {"openclaw": home}}),
    ));
    std::env::remove_var(OPENCLAW_BIN_ENV);
    assert_eq!(response["error"]["code"], -32602, "{response}");
    assert!(
        response["error"]["message"]
            .as_str()
            .is_some_and(|message| message.contains("--workspace")),
        "{response}"
    );
    // Nothing ran: the fake never recorded an argv.
    assert!(argv_log(&root, "openclaw").is_empty());
    std::fs::remove_dir_all(&root).ok();
}

#[test]
fn a_failing_harness_verb_surfaces_its_own_stderr() {
    let _guard = bin_lock();
    let root = scratch_dir("stderr");
    let home = root.join("hermes_home");
    std::fs::create_dir_all(&home).unwrap();
    let cli = write_fake_hermes(&root);
    std::env::set_var(HERMES_BIN_ENV, &cli);
    let mut service = HarnessSessionService::new();
    let response = service.handle(request(
        "harness.v1.profiles.delete",
        json!({
            "harness": "hermes",
            "name": "missing",
            "homes": {"hermes": home.join("state.db")},
        }),
    ));
    std::env::remove_var(HERMES_BIN_ENV);
    let message = response["error"]["message"].as_str().unwrap_or_default();
    assert!(
        message.contains("Profile 'missing' does not exist."),
        "the harness's own stderr must survive: {response}"
    );
    assert!(response.get("result").is_none(), "{response}");
    std::fs::remove_dir_all(&root).ok();
}

#[test]
fn codex_and_supercode_presets_refuse_both_verbs() {
    let mut service = HarnessSessionService::new();
    for (harness, needle) in [("codex", "[profiles.<name>]"), ("supercode", "CODE")] {
        for method in ["harness.v1.profiles.create", "harness.v1.profiles.delete"] {
            let response = service.handle(request(
                method,
                json!({"harness": harness, "name": "review", "workspace": "/tmp/ws"}),
            ));
            assert_eq!(
                response["error"]["code"], -32020,
                "{harness} {method}: {response}"
            );
            let message = response["error"]["message"].as_str().unwrap_or_default();
            assert!(message.contains(needle), "{harness} {method}: {response}");
            assert!(
                response.get("result").is_none(),
                "{harness} {method}: {response}"
            );
        }
    }
}

#[test]
fn a_harness_without_profiles_refuses_with_the_read_sides_sentence() {
    let mut service = HarnessSessionService::new();
    for harness in ["claude-code", "opencode", "pi"] {
        let response = service.handle(request(
            "harness.v1.profiles.create",
            json!({"harness": harness, "name": "coder"}),
        ));
        assert_eq!(response["error"]["code"], -32020, "{harness}: {response}");
        assert!(
            response["error"]["message"]
                .as_str()
                .is_some_and(|message| message.contains("has no profile concept")),
            "{harness}: {response}"
        );
    }
}

#[test]
fn every_controlled_profile_method_is_declared_and_mirrored_by_the_sdk() {
    for verb in ["create", "delete"] {
        let method = format!("harness.v1.profiles.{verb}");
        assert!(
            HARNESS_SERVICE_METHODS.contains(&method.as_str()),
            "{method} is not declared"
        );
        let operation = SdkOperation::from_method(&method)
            .unwrap_or_else(|| panic!("{method} has no SDK operation"));
        assert_eq!(operation.action_name(), format!("profiles_{verb}"));
    }
}

#[test]
fn the_registry_reports_the_controlled_tier_only_where_a_verb_exists() {
    let registry = supercode_harness::harness_support_registry();
    for descriptor in &registry.harnesses {
        let Some(concept) = descriptor
            .orchestration
            .concepts
            .iter()
            .find(|concept| concept.concept == "profile")
        else {
            continue;
        };
        // ORC-13 added the orchestrator: its verb is its own package's
        // operator door, not a CLI, but it is a verb a client can call.
        let controlled = matches!(
            descriptor.id.as_str(),
            "hermes" | "openclaw" | "orchestrator"
        );
        assert_eq!(
            concept.controlled == supercode_harness::support::ImplementationKind::BuiltIn,
            controlled,
            "{}: {concept:?}",
            descriptor.id.as_str()
        );
        if controlled {
            assert!(
                concept
                    .methods
                    .iter()
                    .any(|method| method == "harness.v1.profiles.create"),
                "{}: {concept:?}",
                descriptor.id.as_str()
            );
        }
    }
}