use assert_cmd::Command;
use std::fs;
use std::path::Path;
use std::process::Command as StdCommand;
type TestResult = Result<(), Box<dyn std::error::Error>>;
const MANIFEST: &str = r#"
version = 1
canonical = "json-schema-2020-12"
authoring = "zod"
[[contracts]]
name = "user"
source = "contracts/user.zod.ts"
emit = ["zod"]
[[mappings]]
glob = "app/api/**/*.ts"
contracts = ["user"]
require = "boundary-validation"
[gates]
suppression_comments = "deny"
protected_paths = ["pushkin.toml"]
read_only_paths = ["crates/**/tests/**"]
"#;
const MAPPED: &str = "app/api/users/route.ts";
const COMMITTED_TEST: &str = "crates/pushkin-cli/tests/committed_suite.rs";
const RULE_CONTENT_UNAVAILABLE: &str = "pushkin.content_unavailable";
const RULE_UNVALIDATED: &str = "contract.boundary.unvalidated_input";
const RULE_READ_ONLY: &str = "pushkin.read_only_path";
const CONFORMING: &str = "import { UserCreateSchema } from \"contracts/user.zod\";\n\
export async function POST(req: Request) {\n \
const body = UserCreateSchema.parse(await req.json());\n \
return Response.json(body);\n}\n";
const BREAK_OLD: &str = "const body = UserCreateSchema.parse(await req.json());";
const BREAK_NEW: &str = "const body = await req.json();";
fn git(dir: &Path, args: &[&str]) -> TestResult {
let status = StdCommand::new("git")
.current_dir(dir)
.args(args)
.status()?;
assert!(status.success(), "git {args:?} failed");
Ok(())
}
fn repo() -> Result<tempfile::TempDir, Box<dyn std::error::Error>> {
let dir = tempfile::tempdir()?;
fs::write(dir.path().join("pushkin.toml"), MANIFEST)?;
fs::create_dir_all(dir.path().join("contracts"))?;
fs::write(
dir.path().join("contracts/user.zod.ts"),
"export const user = 1;\n",
)?;
fs::create_dir_all(dir.path().join("app/api/users"))?;
fs::write(dir.path().join(MAPPED), CONFORMING)?;
fs::create_dir_all(dir.path().join("crates/pushkin-cli/tests"))?;
fs::write(dir.path().join(COMMITTED_TEST), "// committed suite\n")?;
git(dir.path(), &["init", "-q", "."])?;
git(dir.path(), &["add", "-A"])?;
git(
dir.path(),
&[
"-c",
"user.name=PhaseB Opencode",
"-c",
"user.email=pb@test",
"commit",
"-qm",
"fixture",
],
)?;
Ok(dir)
}
fn absolute(dir: &Path, relative: &str) -> String {
dir.canonicalize()
.unwrap_or_else(|_| dir.to_path_buf())
.join(relative)
.to_string_lossy()
.into_owned()
}
fn edit_payload(dir: &Path, path: &str, old: &str, new: &str) -> String {
serde_json::json!({
"sessionID": "phase-b-opencode",
"tool": "edit",
"args": { "filePath": absolute(dir, path), "oldString": old, "newString": new },
})
.to_string()
}
fn edit_all_payload(dir: &Path, path: &str, old: &str, new: &str) -> String {
serde_json::json!({
"sessionID": "phase-b-opencode",
"tool": "edit",
"args": {
"filePath": absolute(dir, path),
"oldString": old,
"newString": new,
"replaceAll": true,
},
})
.to_string()
}
fn write_payload(dir: &Path, path: &str, content: &str) -> String {
serde_json::json!({
"sessionID": "phase-b-opencode",
"tool": "write",
"args": { "filePath": absolute(dir, path), "content": content },
})
.to_string()
}
fn hook(
dir: &Path,
payload: &str,
daemon: Option<&str>,
) -> Result<String, Box<dyn std::error::Error>> {
let mut cmd = Command::cargo_bin("pushkin")?;
cmd.current_dir(dir).write_stdin(payload.to_owned());
if let Some(mode) = daemon {
cmd.env("PUSHKIN_DAEMON", mode);
}
let output = cmd.args(["hook", "opencode"]).output()?;
Ok(format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
))
}
#[test]
fn an_edit_that_breaks_the_contract_is_denied_under_the_real_rule() -> TestResult {
let dir = repo()?;
let output = hook(
dir.path(),
&edit_payload(dir.path(), MAPPED, BREAK_OLD, BREAK_NEW),
Some("off"),
)?;
assert!(
output.contains(RULE_UNVALIDATED),
"the synthesized file drops the parse and must be judged on it: {output}"
);
assert!(
!output.contains(RULE_CONTENT_UNAVAILABLE),
"content IS available now — it was synthesized: {output}"
);
Ok(())
}
#[test]
fn an_edit_that_keeps_the_contract_is_allowed() -> TestResult {
let dir = repo()?;
let output = hook(
dir.path(),
&edit_payload(
dir.path(),
MAPPED,
"return Response.json(body);",
"return Response.json({ ...body });",
),
Some("off"),
)?;
assert!(
!output.contains(RULE_UNVALIDATED) && !output.contains(RULE_CONTENT_UNAVAILABLE),
"the synthesized file still parses through the contract: {output}"
);
Ok(())
}
#[test]
fn an_edit_and_the_equivalent_write_reach_the_same_verdict() -> TestResult {
let dir = repo()?;
let synthesized = CONFORMING.replace(BREAK_OLD, BREAK_NEW);
let via_edit = hook(
dir.path(),
&edit_payload(dir.path(), MAPPED, BREAK_OLD, BREAK_NEW),
Some("off"),
)?;
let via_write = hook(
dir.path(),
&write_payload(dir.path(), MAPPED, &synthesized),
Some("off"),
)?;
for output in [&via_edit, &via_write] {
assert!(
output.contains(RULE_UNVALIDATED),
"both routes judge the same bytes: {output}"
);
assert!(
!output.contains(RULE_CONTENT_UNAVAILABLE),
"and judge them, rather than both refusing: {output}"
);
}
Ok(())
}
#[test]
fn an_edit_whose_target_is_missing_falls_back_to_the_interim_refusal() -> TestResult {
let dir = repo()?;
let output = hook(
dir.path(),
&edit_payload(dir.path(), MAPPED, "nowhere in the file", "x"),
Some("off"),
)?;
assert!(
output.contains(RULE_CONTENT_UNAVAILABLE),
"no faithful reconstruction is possible, so refuse: {output}"
);
Ok(())
}
#[test]
fn an_ambiguous_target_falls_back_to_the_interim_refusal() -> TestResult {
let dir = repo()?;
let output = hook(
dir.path(),
&edit_payload(dir.path(), MAPPED, "body", "payload"),
Some("off"),
)?;
assert!(
output.contains(RULE_CONTENT_UNAVAILABLE),
"an ambiguous target must refuse, never pick the first: {output}"
);
Ok(())
}
#[test]
fn replace_all_resolves_an_otherwise_ambiguous_target() -> TestResult {
let dir = repo()?;
let output = hook(
dir.path(),
&edit_all_payload(dir.path(), MAPPED, "body", "payload"),
Some("off"),
)?;
assert!(
!output.contains(RULE_CONTENT_UNAVAILABLE),
"replaceAll says every occurrence was meant, so there is nothing \
ambiguous left to refuse: {output}"
);
Ok(())
}
#[test]
fn a_read_only_path_denies_before_synthesis_is_attempted() -> TestResult {
let dir = repo()?;
let output = hook(
dir.path(),
&edit_payload(dir.path(), COMMITTED_TEST, "committed", "tampered"),
Some("off"),
)?;
assert!(output.contains(RULE_READ_ONLY), "path rule first: {output}");
Ok(())
}
#[test]
fn the_patch_tool_still_reaches_the_read_only_rule() -> TestResult {
let dir = repo()?;
let payload = serde_json::json!({
"sessionID": "phase-b-opencode",
"tool": "apply_patch",
"args": {
"patchText": format!(
"*** Begin Patch\n*** Update File: {COMMITTED_TEST}\n@@\n-a\n+b\n*** End Patch\n"
),
},
})
.to_string();
let output = hook(dir.path(), &payload, Some("off"))?;
assert!(output.contains(RULE_READ_ONLY), "{output}");
Ok(())
}