use std::path::{Path, PathBuf};
use serde_json::json;
use supercode::reduce::{invert, project, verify_log, ReductionLog, ReductionPolicy};
use supercode::sidecar::SidecarWriter;
use supercode::{
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);
}
}
}
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;
}
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 {
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;
}
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/core/src/agent.rs"),
root.join("crates/core/src/sdk.rs"),
root.join("crates/core/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",
" 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/core/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/core/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",
"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::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/core/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/core/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/core/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-core --test sdk_core_semantics",
"cargo test -p supercode-core --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/core/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();
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::Session::load(&reload_path).unwrap();
assert_eq!(
reloaded.meta.session_id.as_deref(),
Some("1e6f2a3b-0000-4000-8000-000000000001")
);
assert!(!reloaded
.to_jsonl(supercode::SessionFormat::Pi)
.unwrap()
.contains("SURFACE_"));
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();
}