supercode-harness 0.4.11

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
use std::path::{Path, PathBuf};

use serde_json::json;
use supercode_harness::reduce::{invert, project, verify_log, ReductionLog, ReductionPolicy};
use supercode_harness::sidecar::SidecarWriter;
use supercode_harness::{
    HarnessId, HarnessSessionService, SdkOperation, SdkRequest, SdkService, Session, SessionFormat,
};

fn repo_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .canonicalize()
        .unwrap()
}

fn production_code(source: &str) -> String {
    let source = source
        .find("#[cfg(test)]\nmod tests")
        .map_or(source, |index| &source[..index]);
    let mut code = String::with_capacity(source.len());
    let mut chars = source.chars().peekable();
    let mut block_comment = false;
    while let Some(ch) = chars.next() {
        if block_comment {
            if ch == '*' && chars.peek() == Some(&'/') {
                chars.next();
                block_comment = false;
            }
            continue;
        }
        if ch == '/' && chars.peek() == Some(&'*') {
            chars.next();
            block_comment = true;
            continue;
        }
        if ch == '/' && chars.peek() == Some(&'/') {
            chars.next();
            for next in chars.by_ref() {
                if next == '\n' {
                    code.push('\n');
                    break;
                }
            }
            continue;
        }
        code.push(ch);
    }
    code
}

fn rust_sources(path: &Path, files: &mut Vec<PathBuf>) {
    for entry in std::fs::read_dir(path).unwrap() {
        let path = entry.unwrap().path();
        if path.is_dir() {
            rust_sources(&path, files);
        } else if path.extension().and_then(|value| value.to_str()) == Some("rs") {
            files.push(path);
        }
    }
}

/// Return Rust identifiers outside comments and string/character literals.
///
/// Architecture guards must reject implementation type imports and uses, but
/// terminal copy is allowed to say words such as "Agent" or "Provider". A
/// lexical identifier scan keeps that display-only vocabulary from becoming a
/// false positive while still catching aliases and fully-qualified paths.
fn production_identifiers(source: &str) -> Vec<String> {
    let code = source
        .find("#[cfg(test)]\nmod tests")
        .map_or(source, |index| &source[..index]);
    let bytes = code.as_bytes();
    let mut identifiers = Vec::new();
    let mut index = 0;
    while index < bytes.len() {
        if bytes.get(index..index + 2) == Some(b"//") {
            index += 2;
            while index < bytes.len() && bytes[index] != b'\n' {
                index += 1;
            }
            continue;
        }
        if bytes.get(index..index + 2) == Some(b"/*") {
            index += 2;
            let mut depth = 1usize;
            while index < bytes.len() && depth > 0 {
                if bytes.get(index..index + 2) == Some(b"/*") {
                    depth += 1;
                    index += 2;
                } else if bytes.get(index..index + 2) == Some(b"*/") {
                    depth -= 1;
                    index += 2;
                } else {
                    index += 1;
                }
            }
            continue;
        }

        // Ordinary strings, byte strings, and character/byte literals.
        let quote = if bytes[index] == b'"' || bytes[index] == b'\'' {
            Some(bytes[index])
        } else if bytes[index] == b'b'
            && index + 1 < bytes.len()
            && matches!(bytes[index + 1], b'"' | b'\'')
        {
            index += 1;
            Some(bytes[index])
        } else {
            None
        };
        if let Some(quote) = quote {
            // A leading apostrophe followed by an identifier is a lifetime,
            // not a character literal. Let the identifier scanner see it.
            if quote == b'\''
                && index + 1 < bytes.len()
                && (bytes[index + 1].is_ascii_alphabetic() || bytes[index + 1] == b'_')
                && bytes[index + 1..]
                    .iter()
                    .position(|byte| !byte.is_ascii_alphanumeric() && *byte != b'_')
                    .is_none_or(|offset| bytes[index + 1 + offset] != b'\'')
            {
                index += 1;
                continue;
            }
            index += 1;
            while index < bytes.len() {
                if bytes[index] == b'\\' {
                    index = (index + 2).min(bytes.len());
                } else if bytes[index] == quote {
                    index += 1;
                    break;
                } else {
                    index += 1;
                }
            }
            continue;
        }

        // Raw strings and raw byte strings: r"...", r#"..."#, br#"..."#.
        let raw_start = if bytes[index] == b'r' {
            Some(index + 1)
        } else if bytes[index] == b'b' && index + 1 < bytes.len() && bytes[index + 1] == b'r' {
            Some(index + 2)
        } else {
            None
        };
        if let Some(mut cursor) = raw_start {
            let mut hashes = 0;
            while cursor < bytes.len() && bytes[cursor] == b'#' {
                hashes += 1;
                cursor += 1;
            }
            if cursor < bytes.len() && bytes[cursor] == b'"' {
                cursor += 1;
                while cursor < bytes.len() {
                    if bytes[cursor] == b'"'
                        && bytes.get(cursor + 1..cursor + 1 + hashes)
                            == Some(&vec![b'#'; hashes][..])
                    {
                        index = cursor + 1 + hashes;
                        break;
                    }
                    cursor += 1;
                }
                if cursor >= bytes.len() {
                    index = bytes.len();
                }
                continue;
            }
        }

        if bytes[index].is_ascii_alphabetic() || bytes[index] == b'_' {
            let start = index;
            index += 1;
            while index < bytes.len()
                && (bytes[index].is_ascii_alphanumeric() || bytes[index] == b'_')
            {
                index += 1;
            }
            identifiers.push(code[start..index].to_string());
        } else {
            index += 1;
        }
    }
    identifiers
}

#[test]
fn public_surfaces_cannot_construct_or_drive_a_second_agent_loop() {
    let root = repo_root();
    let approved = [
        root.join("crates/harness/src/agent.rs"),
        root.join("crates/harness/src/sdk.rs"),
        root.join("crates/harness/src/server.rs"),
    ];
    let mut sources = Vec::new();
    for entry in std::fs::read_dir(root.join("crates")).unwrap() {
        let source_dir = entry.unwrap().path().join("src");
        if source_dir.is_dir() {
            rust_sources(&source_dir, &mut sources);
        }
    }
    for path in sources {
        if approved.contains(&path) {
            continue;
        }
        let code = production_code(&std::fs::read_to_string(&path).unwrap());
        for forbidden in [
            "Agent::new(",
            "Agent::resume(",
            "Agent::resume_recorded(",
            "Agent::with_provider",
            "Agent::with_parts(",
            "agent.send(",
            "agent.send_with_images(",
            ".run_loop(",
        ] {
            assert!(
                !code.contains(forbidden),
                "{} bypassed supercode.sdk.v1 through `{forbidden}`",
                path.display()
            );
        }
    }

    let cli =
        production_code(&std::fs::read_to_string(root.join("crates/cli/src/main.rs")).unwrap());
    for forbidden in [
        "use supercode::Agent",
        "use supercode_harness::Agent",
        " Agent,",
        "&Agent,",
        "&Agent)",
        "&Agent ",
        "&mut Agent",
        "agent.send(",
        "agent.send_with_images(",
    ] {
        assert!(
            !cli.contains(forbidden),
            "CLI owns raw Agent via `{forbidden}`"
        );
    }
    for required in [
        "SdkAgent",
        "supercode::create_agent(",
        "supercode::resume_agent(",
        "supercode::submit_agent(",
    ] {
        assert!(cli.contains(required), "CLI omitted SDK seam `{required}`");
    }

    let acp = std::fs::read_to_string(root.join("crates/harness/src/acp_server.rs")).unwrap();
    let acp = production_code(&acp);
    assert!(acp.contains("dyn SdkRuntime"));
    assert!(
        !acp.contains("reqwest::"),
        "ACP must reuse the SDK HTTP adapter"
    );
    assert!(
        !acp.contains("trait AcpRuntime"),
        "ACP must not own a runtime contract"
    );

    let mcp = std::fs::read_to_string(root.join("crates/harness/src/mcp.rs")).unwrap();
    assert!(mcp.contains("impl Tool for SdkMcpTool"));
    assert!(mcp.contains(".execute(SdkRequest"));

    let frontend_root = root.join("crates/frontend-tui/src");
    let mut frontend_sources = Vec::new();
    rust_sources(&frontend_root, &mut frontend_sources);
    let forbidden_frontend_identifiers = [
        // Agent/provider execution internals.
        "Agent",
        "Provider",
        // Persistence, native import/export, scheduler, and reduction
        // implementation types. Frontends may consume semantic facade types
        // and display these words in strings, but may never import/use these
        // identifiers as production Rust code.
        "HarnessSessionService",
        "SessionCatalog",
        "SessionFormat",
        "SessionLocator",
        "SessionStore",
        "SidecarWriter",
        "ReductionLog",
        "ReductionPolicy",
        "Scheduler",
        "export_session",
        "import_session",
    ];
    let display_only = production_identifiers(
        r##"const LABEL: &str = "Agent Provider SessionStore ReductionLog";
            const RAW_LABEL: &str = r#"Scheduler SessionFormat // display only"#;
            use supercode_harness::FrontendRuntime;"##,
    );
    assert!(display_only
        .iter()
        .any(|identifier| identifier == "FrontendRuntime"));
    assert!(forbidden_frontend_identifiers
        .iter()
        .all(|forbidden| !display_only
            .iter()
            .any(|identifier| identifier == forbidden)));
    for path in &frontend_sources {
        let source = std::fs::read_to_string(path).unwrap();
        let identifiers = production_identifiers(&source);
        for forbidden in forbidden_frontend_identifiers {
            assert!(
                !identifiers.iter().any(|identifier| identifier == forbidden),
                "embedded frontend production source {} reaches forbidden runtime implementation identifier `{forbidden}`",
                path.display()
            );
        }
    }
    let frontend =
        production_code(&std::fs::read_to_string(frontend_root.join("runtime.rs")).unwrap());
    assert!(frontend.contains("dyn FrontendRuntime"));

    let sdk = std::fs::read_to_string(root.join("crates/harness/src/sdk.rs")).unwrap();
    assert!(sdk.contains("pub trait SdkRuntime"));
    assert!(!sdk.contains("impl Deref for SdkAgent"));
    assert!(!sdk.contains("impl DerefMut for SdkAgent"));
    let frontend_contract =
        std::fs::read_to_string(root.join("crates/harness/src/frontend.rs")).unwrap();
    assert!(!frontend_contract.contains("pub trait FrontendRuntime"));
    assert!(!frontend_contract.contains("pub struct FrontendEvent"));
    assert!(!frontend_contract.contains("pub enum FrontendRuntimeError"));
    for outward in ["acp_server", "crate::mcp", "frontend_tui", "crates::cli"] {
        assert!(!sdk.contains(outward), "SDK depends outward on `{outward}`");
    }

    let typescript = std::fs::read_to_string(root.join("sdk/typescript/client.mjs")).unwrap();
    for operation in SdkOperation::ALL {
        if let Some(method) = operation.method() {
            assert!(
                typescript.contains(method),
                "TypeScript adapter omitted SDK method `{method}`"
            );
        }
    }
}

#[test]
fn independent_adapter_removal_receipt_covers_every_feature_and_sdk_semantics() {
    let root = repo_root();
    let manifest = std::fs::read_to_string(root.join("crates/harness/Cargo.toml")).unwrap();
    for feature in ["adapter-api", "adapter-mcp", "adapter-acp"] {
        assert!(
            manifest.contains(feature),
            "missing removable `{feature}` seam"
        );
    }
    let receipt =
        std::fs::read_to_string(root.join("scripts/check-sdk-adapter-removability.sh")).unwrap();
    for command in [
        "cargo check -p supercode-core --no-default-features\n",
        "--features adapter-mcp,adapter-acp",
        "--features adapter-api,adapter-acp",
        "--features adapter-api,adapter-mcp",
        "cargo test -p supercode-harness --test sdk_core_semantics",
        "cargo test -p supercode-harness --no-default-features --test sdk_core_semantics",
        "cargo check -p supercode-frontend-model",
        "cargo check -p supercode-cli",
        "cargo check -p supercode-frontend-tui",
        "npm test --prefix sdk/frontend",
    ] {
        assert!(
            receipt.contains(command),
            "removal receipt omitted `{command}`"
        );
    }
}

#[tokio::test]
async fn transport_envelopes_never_enter_canonical_or_exported_sessions() {
    let root = repo_root();
    let fixture_path = root.join("crates/harness/tests/fixtures/pi_session.jsonl");
    let locator = json!({
        "harness": HarnessId::PI,
        "session_id": "1e6f2a3b-0000-4000-8000-000000000001",
        "storage": {
            "kind": "file",
            "path": fixture_path,
        },
    });
    let sentinels = json!({
        "jsonrpc_id": "SURFACE_JSON_RPC_SENTINEL",
        "mcp_tool_call_id": "SURFACE_MCP_SENTINEL",
        "acp_session_update": "SURFACE_ACP_SENTINEL",
        "ui_text": "SURFACE_UI_TEXT_SENTINEL",
        "ansi": "SURFACE_ANSI_SENTINEL",
        "layout": "SURFACE_LAYOUT_SENTINEL",
        "palette": "SURFACE_PALETTE_SENTINEL",
        "client_identity": "SURFACE_CLIENT_ID_SENTINEL",
        "compatibility": "SURFACE_COMPATIBILITY_SENTINEL",
    });
    let mut service = HarnessSessionService::new();

    let loaded = service
        .execute(SdkRequest {
            operation: SdkOperation::Load,
            params: json!({"locator": locator, "_surface": sentinels}),
        })
        .await
        .unwrap();
    let canonical = serde_json::to_string(&loaded).unwrap();

    let exported = service
        .execute(SdkRequest {
            operation: SdkOperation::Export,
            params: json!({
                "locator": locator,
                "target_harness": "pi",
                "_surface": sentinels,
            }),
        })
        .await
        .unwrap();
    let native_export = exported["artifact"]["content"].as_str().unwrap();

    let reload_dir = std::env::temp_dir().join(format!(
        "supercode-sdk-envelope-reload-{}",
        std::process::id()
    ));
    std::fs::create_dir_all(&reload_dir).unwrap();

    // Materialize the exact native session family files used by reduced
    // continuation: append-only sidecar plus persisted reduction log.
    let source_session = Session::load(&fixture_path).unwrap();
    let sidecar_path = reload_dir.join("surface-proof.sidecar.jsonl");
    {
        let _writer = SidecarWriter::create(&sidecar_path, &source_session).unwrap();
    }
    let sidecar_bytes = std::fs::read_to_string(&sidecar_path).unwrap();
    let reloaded_sidecar = Session::from_sidecar_str(&sidecar_bytes).unwrap();
    let proof_policy = ReductionPolicy {
        image_redact_min_bytes: 0,
        ..ReductionPolicy::default()
    };
    let (view, log) = project(&reloaded_sidecar, &proof_policy, &ReductionLog::default());
    let reduction_path = reload_dir.join("surface-proof.reduction.json");
    std::fs::write(&reduction_path, serde_json::to_vec_pretty(&log).unwrap()).unwrap();
    let reduction_bytes = std::fs::read_to_string(&reduction_path).unwrap();
    let reloaded_log: ReductionLog = serde_json::from_str(&reduction_bytes).unwrap();
    assert!(
        !reloaded_log.reductions.is_empty(),
        "metadata proof requires a non-empty persisted reduction index"
    );

    for sentinel in [
        "SURFACE_JSON_RPC_SENTINEL",
        "SURFACE_MCP_SENTINEL",
        "SURFACE_ACP_SENTINEL",
        "SURFACE_UI_TEXT_SENTINEL",
        "SURFACE_ANSI_SENTINEL",
        "SURFACE_LAYOUT_SENTINEL",
        "SURFACE_PALETTE_SENTINEL",
        "SURFACE_CLIENT_ID_SENTINEL",
        "SURFACE_COMPATIBILITY_SENTINEL",
    ] {
        assert!(!canonical.contains(sentinel));
        assert!(!native_export.contains(sentinel));
        assert!(!sidecar_bytes.contains(sentinel));
        assert!(!reduction_bytes.contains(sentinel));
    }

    let reload_path = reload_dir.join("exported-pi.jsonl");
    std::fs::write(&reload_path, native_export).unwrap();
    let reloaded = supercode_harness::Session::load(&reload_path).unwrap();
    assert_eq!(
        reloaded.meta.session_id.as_deref(),
        Some("1e6f2a3b-0000-4000-8000-000000000001")
    );
    assert!(!reloaded
        .to_jsonl(supercode_harness::SessionFormat::Pi)
        .unwrap()
        .contains("SURFACE_"));

    // The disk artifacts remain a valid reversible reduced family after the
    // negative metadata proof; this catches a vacuous empty/corrupt sidecar or
    // log that merely happened not to contain the sentinels.
    verify_log(&reloaded_log, &reloaded_sidecar).unwrap();
    let restored = invert(&view, &reloaded_log, &reloaded_sidecar).unwrap();
    assert_eq!(restored, reloaded_sidecar.messages);
    assert_eq!(
        reloaded_sidecar.to_jsonl(SessionFormat::Pi).unwrap(),
        source_session.to_jsonl(SessionFormat::Pi).unwrap()
    );
    std::fs::remove_dir_all(reload_dir).ok();
}