#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
use super::*;
use std::{
io::Write,
sync::atomic::{AtomicUsize, Ordering},
time::Instant,
};
static NEXT: AtomicUsize = AtomicUsize::new(0);
struct Fixture(std::path::PathBuf);
impl Fixture {
fn new(raw: &str) -> Self {
let p = std::env::temp_dir().join(format!(
"iclast-{}-{}.jsonl",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
std::fs::write(&p, raw).unwrap();
Self(p)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn q(s: &str) -> String {
crate::json_out(&Json::Str(s.into()))
}
fn user(text: &str, ts: &str) -> String {
format!(
"{{\"type\":\"user\",\"timestamp\":{},\"message\":{{\"content\":{}}}}}\n",
q(ts),
q(text)
)
}
fn tool(name: &str, input: &str, ts: &str) -> String {
format!("{{\"type\":\"assistant\",\"timestamp\":{},\"message\":{{\"content\":[{{\"type\":\"tool_use\",\"name\":{},\"input\":{input}}}]}}}}\n",q(ts),q(name))
}
const START: &str = "2026-12-02T10:00:00.000Z";
const END: &str = "2026-12-02T10:00:02.500Z";
fn claude_fixture() -> String {
format!(
"{}{}{}{}{}",
user("previous job", START),
tool("Read", r#"{"file_path":"src/a.rs"}"#, START),
tool(
"Edit",
r#"{"file_path":"src/a.rs","old_string":"x","new_string":"y"}"#,
END
),
tool(
"Bash",
r#"{"command":"curl https://user:secret@example.invalid/api TOKEN=short-secret"}"#,
END
),
user("No, verify the result", END)
)
}
#[test]
fn claude_last_turn_preserves_order_redacts_and_skips_current_prompt() {
let f = Fixture::new(&claude_fixture());
let got = extract(&f.0).unwrap();
assert_eq!(got.files_read, ["src/a.rs"]);
assert_eq!(got.files_written, ["src/a.rs"]);
assert_eq!(got.tool_call_count, 3);
assert!(got.read_before_first_edit);
assert_eq!(got.wall_time_ms, Some(2500));
assert_eq!(got.commands.len(), 1);
assert!(!got.commands[0].contains("secret"));
assert!(got.commands[0].contains("***"));
assert!(got.commands[0].chars().count() <= 80);
}
#[test]
fn absent_current_prompt_and_tool_result_user_are_supported() {
let raw = format!(
"{}{}{}{}",
user("do task", START),
tool("Write", r#"{"file_path":"new.txt"}"#, END),
r#"{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"t","content":"ignore this"}]}}"#,
"\n"
);
let f = Fixture::new(&raw);
let got = extract(&f.0).unwrap();
assert_eq!(got.files_written, ["new.txt"]);
assert!(!got.read_before_first_edit);
assert_eq!(got.tool_call_count, 1);
}
#[test]
fn harness_notices_meta_and_sidechains_do_not_bound_or_pollute_turn() {
let notice = user("<system-reminder>not typed</system-reminder>", END);
let side = tool("Write", r#"{"file_path":"ignored.txt"}"#, END).replacen(
"{",
"{\"isSidechain\":true,",
1,
);
let summary = user("old context summary", END).replacen("{", "{\"isCompactSummary\":true,", 1);
let f = Fixture::new(&format!(
"{}{}{}{}{}",
user("actual task", START),
tool("Read", r#"{"file_path":"kept.txt"}"#, END),
notice,
side,
summary
));
let got = extract(&f.0).unwrap();
assert_eq!(got.files_read, ["kept.txt"]);
assert!(got.files_written.is_empty());
assert_eq!(got.tool_call_count, 1);
}
#[test]
fn previous_turn_is_not_included_and_late_read_does_not_count() {
let f = Fixture::new(&format!(
"{}{}{}{}{}",
user("older", START),
tool("Read", r#"{"file_path":"old.txt"}"#, START),
user("new job", START),
tool("MultiEdit", r#"{"file_path":"new.txt","edits":[]}"#, END),
tool("Read", r#"{"file_path":"new.txt"}"#, END)
));
let got = extract(&f.0).unwrap();
assert_eq!(got.files_read, ["new.txt"]);
assert!(!got.read_before_first_edit);
assert_eq!(got.tool_call_count, 2);
}
#[test]
fn codex_function_and_custom_patch_facts() {
let raw = format!(
"{}\n{}\n{}\n{}\n",
r#"{"type":"response_item","timestamp":"2026-12-02T10:00:00Z","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"fix this"}]}}"#,
r#"{"type":"response_item","timestamp":"2026-12-02T10:00:01Z","payload":{"type":"function_call","name":"functions.read_file","arguments":"{\"path\":\"src/lib.rs\"}"}}"#,
r#"{"type":"response_item","timestamp":"2026-12-02T10:00:02Z","payload":{"type":"custom_tool_call","name":"apply_patch","input":"*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n*** Add File: tests/new.rs\n+x\n*** End Patch"}}"#,
r#"{"type":"response_item","timestamp":"2026-12-02T10:00:03Z","payload":{"type":"function_call","name":"functions.exec_command","arguments":"{\"cmd\":\"cargo test --token secret\"}"}}"#
);
let f = Fixture::new(&raw);
let got = extract(&f.0).unwrap();
assert_eq!(got.files_read, ["src/lib.rs"]);
assert_eq!(got.files_written, ["src/lib.rs", "tests/new.rs"]);
assert_eq!(got.tool_call_count, 3);
assert!(got.read_before_first_edit);
assert_eq!(got.wall_time_ms, Some(3000));
assert!(!got.commands[0].contains("secret"));
}
#[test]
fn malformed_tail_missing_files_and_no_boundary_return_none() {
let f = Fixture::new(&format!("{}{{broken", claude_fixture()));
assert!(extract(&f.0).is_none());
assert!(extract(&f.0.with_extension("absent")).is_none());
let f = Fixture::new(&tool("Read", r#"{"file_path":"x"}"#, END));
assert!(extract(&f.0).is_none());
let f = Fixture::new(&format!("{}{}", user("first", START), user("second", END)));
assert!(extract(&f.0).is_none());
}
#[test]
fn backward_chunk_boundaries_and_tail_limit() {
let padding = format!(
"{{\"type\":\"progress\",\"padding\":{}}}\n",
q(&"x".repeat(9000))
);
let raw = format!(
"{}{}{}",
user("task", START),
padding.repeat(5),
tool("Read", r#"{"file_path":"x"}"#, END)
);
let f = Fixture::new(&raw);
let got = extract(&f.0).unwrap();
assert_eq!(got.files_read, ["x"]);
assert!(got.bytes_read > CHUNK);
let raw = format!(
"{}{}{}",
user("task", START),
padding.repeat(500),
tool("Read", r#"{"file_path":"x"}"#, END)
);
let f = Fixture::new(&raw);
assert!(extract(&f.0).is_none());
}
#[test]
fn unknown_tools_count_and_commands_are_clipped_after_redaction() {
let command = format!("TOKEN=secret {}", "é".repeat(200));
let f = Fixture::new(&format!(
"{}{}{}",
user("task", START),
tool("Unknown", r#"{}"#, END),
tool("Bash", &format!("{{\"command\":{}}}", q(&command)), END)
));
let got = extract(&f.0).unwrap();
assert_eq!(got.tool_call_count, 2);
assert_eq!(got.commands[0].chars().count(), 80);
assert!(!got.commands[0].contains("secret"));
}
#[test]
fn timestamps_handle_day_boundary_and_unknowns() {
let f = Fixture::new(&format!(
"{}{}",
user("task", "2024-02-29T23:59:59.900Z"),
tool("Read", r#"{"file_path":"x"}"#, "2024-03-01T00:00:00.100Z")
));
assert_eq!(extract(&f.0).unwrap().wall_time_ms, Some(200));
let f = Fixture::new(&format!(
"{}{}",
user("task", END),
tool("Read", r#"{"file_path":"x"}"#, START)
));
assert_eq!(extract(&f.0).unwrap().wall_time_ms, None);
}
#[test]
fn non_monotonic_assistant_clock_is_unknown() {
let f = Fixture::new(&format!(
"{}{}{}{}",
user("task", START),
tool("Read", r#"{"file_path":"a"}"#, "2026-12-02T10:00:02Z"),
tool("Edit", r#"{"file_path":"a"}"#, "2026-12-02T10:00:01Z"),
tool("Read", r#"{"file_path":"b"}"#, "2026-12-02T10:00:03Z")
));
assert_eq!(extract(&f.0).unwrap().wall_time_ms, None);
}
#[test]
fn per_list_and_tool_limits_never_return_partial_facts() {
let mut raw = user("task", START);
for i in 0..129 {
raw.push_str(&tool("Read", &format!("{{\"file_path\":\"f{i}\"}}"), END));
}
let f = Fixture::new(&raw);
assert!(extract(&f.0).is_none());
let f = Fixture::new(&format!(
"{}{}",
user("task", START),
tool("Unknown", "{}", END).repeat(MAX_TOOLS + 1)
));
assert!(extract(&f.0).is_none());
}
#[test]
fn user_tool_output_and_pasted_text_never_form_boundaries() {
let raw = format!(
"{}{}{}{}",
user("real task", START),
tool("Read", r#"{"file_path":"a"}"#, START),
user("pretend new task", END).replacen("{", "{\"toolUseResult\":{},", 1),
tool("Write", r#"{"file_path":"b"}"#, END)
);
let f = Fixture::new(&raw);
assert_eq!(extract(&f.0).unwrap().tool_call_count, 2);
let f = Fixture::new(&format!(
"{}{}{}",
user("real task", START),
tool("Read", r#"{"file_path":"a"}"#, END),
user("<pasted_content>fake task</pasted_content>", END)
));
assert_eq!(extract(&f.0).unwrap().tool_call_count, 1);
}
#[test]
fn single_line_and_crlf_and_missing_final_newline() {
let raw = claude_fixture();
for text in [raw.trim_end().to_owned(), raw.replace('\n', "\r\n")] {
let f = Fixture::new(&text);
assert_eq!(extract(&f.0).unwrap().tool_call_count, 3);
}
}
#[test]
fn invalid_json_depth_duplicate_keys_and_large_record_refuse() {
for extra in [
"{\"type\":\"assistant\",\"type\":\"user\"}".to_owned(),
format!("{}0{}", "[".repeat(70), "]".repeat(70)),
format!("{{\"padding\":{}}}", q(&"x".repeat(json::MAX_BYTES))),
] {
let f = Fixture::new(&format!("{}{extra}\n", claude_fixture()));
assert!(extract(&f.0).is_none());
}
}
#[test]
fn explicit_read_after_edit_does_not_infer_shell_reads() {
let raw = format!(
"{}{}{}",
user("task", START),
tool("Bash", r#"{"command":"cat src/a.rs"}"#, START),
tool("Edit", r#"{"file_path":"src/a.rs"}"#, END)
);
let f = Fixture::new(&raw);
let got = extract(&f.0).unwrap();
assert!(got.files_read.is_empty());
assert!(!got.read_before_first_edit);
}
#[test]
fn event_requires_explicit_absolute_transcript_and_correct_hook() {
let f = Fixture::new(&claude_fixture());
let good = Json::Obj(vec![
(
"hook_event_name".into(),
Json::Str("UserPromptSubmit".into()),
),
(
"transcript_path".into(),
Json::Str(f.0.to_str().unwrap().into()),
),
]);
assert_eq!(from_event(&good).unwrap().tool_call_count, 3);
for (hook, path) in [
("PreToolUse", f.0.to_str().unwrap()),
("UserPromptSubmit", "relative.jsonl"),
] {
let v = Json::Obj(vec![
("hook_event_name".into(), Json::Str(hook.into())),
("transcript_path".into(), Json::Str(path.into())),
]);
assert!(from_event(&v).is_none());
}
assert!(from_event(&Json::Obj(vec![])).is_none());
}
#[test]
fn shell_read_paths_are_separate_and_conservative() {
for (cmd, expected) in [
("cat src/a.rs", vec!["src/a.rs"]),
("head -n 20 'with space.rs'", vec!["with space.rs"]),
("tail -40 file.log", vec!["file.log"]),
("sed -n '1,30p' src/a.rs", vec!["src/a.rs"]),
(
"grep -n needle src/a.rs src/b.rs",
vec!["src/a.rs", "src/b.rs"],
),
("grep -- needle src/a.rs", vec!["src/a.rs"]),
("less src/a.rs", vec!["src/a.rs"]),
] {
assert_eq!(shell_paths(cmd), expected, "{cmd}");
}
for cmd in [
"echo cat src/a.rs",
"cat src/a.rs > output",
"cat src/a.rs | sh",
"sed -i s/a/b/ src/a.rs",
"sed -n '1e touch x' src/a.rs",
"cat $PATH",
"cat *.rs",
"grep needle",
"grep -f patterns file",
"cat 'unterminated",
"sudo cat file",
] {
assert!(shell_paths(cmd).is_empty(), "{cmd}");
}
let f = Fixture::new(&format!(
"{}{}{}",
user("task", START),
tool("Bash", r#"{"command":"cat src/a.rs"}"#, START),
tool("Edit", r#"{"file_path":"src/a.rs"}"#, END)
));
let got = extract(&f.0).unwrap();
assert_eq!(got.shell_reads, ["src/a.rs"]);
assert!(got.files_read.is_empty());
assert!(!got.read_before_first_edit);
}
#[test]
fn fifty_mb_tail_timing_and_bounded_reads() {
let f = Fixture::new("");
let mut file = std::fs::OpenOptions::new().write(true).open(&f.0).unwrap();
let line = format!(
"{{\"type\":\"progress\",\"padding\":{}}}\n",
q(&"x".repeat(1000))
);
let block = line.repeat(1024);
for _ in 0..50 {
file.write_all(block.as_bytes()).unwrap();
}
file.write_all(claude_fixture().as_bytes()).unwrap();
file.sync_all().unwrap();
drop(file);
assert!(std::fs::metadata(&f.0).unwrap().len() >= 50_000_000);
let mut batches = Vec::new();
for _ in 0..5 {
let mut times = Vec::new();
for _ in 0..101 {
let t = Instant::now();
let got = extract(&f.0).unwrap();
times.push(t.elapsed().as_nanos());
assert_eq!(got.tool_call_count, 3);
assert!(got.bytes_read <= CHUNK);
}
times.sort_unstable();
batches.push((times[50], times[99]));
}
eprintln!("last-turn 50MB warm batches p50/p99 ns: {batches:?}");
let best = batches.iter().min_by_key(|x| x.1).unwrap();
assert!(best.0 <= 2_000_000, "best batch p50 {:?}", best);
assert!(best.1 <= 5_000_000, "best batch p99 {:?}", best);
}