#![recursion_limit = "256"]
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use harn_vm::bridge::HostBridge;
use harn_vm::value::VmError;
fn run_with_bridge(source: &str) -> Result<String, String> {
harn_vm::reset_thread_local_state();
let chunk = harn_vm::compile_source(source)?;
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| e.to_string())?;
rt.block_on(async {
let local = tokio::task::LocalSet::new();
local
.run_until(async {
let bridge = Arc::new(HostBridge::from_parts(
Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new())),
Arc::new(AtomicBool::new(false)),
Arc::new(Mutex::new(())),
1,
));
harn_vm::llm::install_current_host_bridge(bridge.clone());
let mut vm = harn_vm::Vm::new();
harn_vm::register_vm_stdlib(&mut vm);
let result = vm
.execute(&chunk)
.await
.map_err(|e: VmError| format!("{e:?}"));
harn_vm::llm::clear_current_host_bridge();
result?;
Ok(vm.output().to_string())
})
.await
})
}
fn out_lines(raw: &str) -> Vec<String> {
raw.lines()
.filter_map(|l| l.strip_prefix("[harn] "))
.map(|s| s.to_string())
.collect()
}
fn race_window_pipeline(session_id: &str, push_stop_before_dispatch: bool) -> String {
let push_line = if push_stop_before_dispatch {
format!(
r#" agent_session_push_bridge_injection(
"{session_id}",
{{body: "STOP — abort the push", mode: "interrupt_immediate", role_hint: "system"}},
)"#
)
} else {
String::new()
};
format!(
r#"
import {{ agent_session_push_bridge_injection }} from "std/agent/state"
pipeline main(task) {{
clear_tool_hooks()
let registry = tool_registry()
let handler_calls = shared_cell({{scope: "task_group", key: "handler-{session_id}", initial: 0}})
let tools = tool_define(
registry,
"would_force_push",
"Test stand-in for an irreversible side-effect tool.",
{{
parameters: {{}},
handler: {{ _args ->
let hsnap = shared_snapshot(handler_calls)
shared_cas(handler_calls, hsnap, hsnap.value + 1)
return "would have force-pushed"
}},
}},
)
let iteration_state = shared_cell({{scope: "task_group", key: "iter-{session_id}", initial: 0}})
let mock_llm = {{ _call ->
let snap = shared_snapshot(iteration_state)
let n = snap.value
shared_cas(iteration_state, snap, n + 1)
if n == 0 {{
{push_line}
return {{
ok: true,
value: {{
text: "",
tool_calls: [{{id: "call_1", name: "would_force_push", arguments: {{}}}}],
provider: "mock",
model: "mock",
}},
}}
}}
return {{
ok: true,
value: {{text: "acknowledged ##DONE##", tool_calls: [], provider: "mock", model: "mock"}},
}}
}}
let result = agent_loop(
"do the push",
nil,
{{
provider: "mock",
tools: tools,
tool_format: "native",
max_iterations: 4,
loop_until_done: true,
session_id: "{session_id}",
llm_caller: mock_llm,
}},
)
log(result.status)
let checkpoints = transcript_events_by_kind(result.transcript, "loop_checkpoint")
var skipped_count = 0
for event in checkpoints {{
if event?.metadata?.dispatch_skipped == true {{
skipped_count = skipped_count + 1
}}
}}
log(skipped_count)
let stats = transcript_stats(result.transcript)
log(stats.tool_result_message_count)
log(shared_get(handler_calls))
let messages = transcript_messages(result.transcript)
var placeholder_count = 0
for message in messages {{
let role = message?.role ?? ""
if role == "tool" || role == "tool_result" {{
if contains(to_string(message?.content ?? ""), "was not dispatched: interrupted") {{
placeholder_count = placeholder_count + 1
}}
}}
}}
log(placeholder_count)
}}
"#
)
}
#[test]
fn pre_tool_dispatch_skips_when_interrupt_immediate_queued_mid_turn() {
let raw = run_with_bridge(&race_window_pipeline("race-window-stops-dispatch", true))
.expect("script must run");
let lines = out_lines(&raw);
assert_eq!(lines[0], "done", "lines: {lines:?}");
assert_eq!(
lines[1], "1",
"expected one skipped dispatch; lines: {lines:?}"
);
assert_eq!(
lines[2], "1",
"expected the synthesized placeholder tool_result; lines: {lines:?}"
);
assert_eq!(
lines[3], "0",
"the tool must not actually run; lines: {lines:?}"
);
assert_eq!(
lines[4], "1",
"placeholder should carry the interrupted marker; lines: {lines:?}"
);
}
#[test]
fn pre_tool_dispatch_dispatches_when_no_injection_queued() {
let raw = run_with_bridge(&race_window_pipeline("race-window-no-stop", false))
.expect("script must run");
let lines = out_lines(&raw);
assert_eq!(lines[0], "done", "lines: {lines:?}");
assert_eq!(
lines[1], "0",
"expected no skipped dispatch; lines: {lines:?}"
);
assert_eq!(
lines[2], "1",
"expected one tool dispatch; lines: {lines:?}"
);
assert_eq!(
lines[3], "1",
"the tool handler should run once; lines: {lines:?}"
);
assert_eq!(
lines[4], "0",
"control run must not synthesize placeholders; lines: {lines:?}"
);
}
fn audit_only_pipeline(session_id: &str, queue_audit_only: bool) -> String {
let push_block = if queue_audit_only {
format!(
r#" agent_session_push_bridge_injection(
"{session_id}",
{{body: "audit trail: agent finished the merge", mode: "audit_only", role_hint: "system"}},
)"#
)
} else {
String::new()
};
format!(
r#"
import {{ agent_session_push_bridge_injection }} from "std/agent/state"
pipeline main(task) {{
clear_tool_hooks()
{push_block}
let call_counter = shared_cell(
{{scope: "task_group", key: "audit-only-llm-calls-{session_id}", initial: 0}},
)
let stub_llm = {{ _call ->
let snap = shared_snapshot(call_counter)
shared_cas(call_counter, snap, snap.value + 1)
return {{
ok: true,
value: {{text: "all set ##DONE##", tool_calls: [], provider: "mock", model: "mock"}},
}}
}}
let result = agent_loop(
"wrap up",
nil,
{{
provider: "mock",
max_iterations: 2,
loop_until_done: true,
session_id: "{session_id}",
llm_caller: stub_llm,
}},
)
log(result.status)
log(shared_get(call_counter))
let reminder_events = transcript_events_by_kind(result.transcript, "system_reminder")
var saw_audit_reminder = false
for event in reminder_events {{
if event?.reminder?.body == "audit trail: agent finished the merge" {{
saw_audit_reminder = true
}}
}}
log(saw_audit_reminder)
let checkpoints = transcript_events_by_kind(result.transcript, "loop_checkpoint")
var loop_exit_deliveries = 0
for event in checkpoints {{
if event?.metadata?.kind == "loop_exit" && (event?.metadata?.delivered ?? 0) >= 1 {{
loop_exit_deliveries = loop_exit_deliveries + 1
}}
}}
log(loop_exit_deliveries)
}}
"#
)
}
#[test]
fn audit_only_reminder_lands_in_transcript_but_model_never_sees_it() {
let raw =
run_with_bridge(&audit_only_pipeline("audit-only-records", true)).expect("script must run");
let lines = out_lines(&raw);
assert_eq!(lines[0], "done", "lines: {lines:?}");
assert_eq!(
lines[1], "1",
"expected exactly one LLM call; lines: {lines:?}"
);
assert_eq!(
lines[2], "true",
"audit_only reminder should land in transcript audit; lines: {lines:?}"
);
assert_eq!(
lines[3], "1",
"loop_exit checkpoint should report the delivery; lines: {lines:?}"
);
}
#[test]
fn audit_only_control_run_records_no_audit_reminder() {
let raw = run_with_bridge(&audit_only_pipeline("audit-only-control", false))
.expect("script must run");
let lines = out_lines(&raw);
assert_eq!(lines[0], "done", "lines: {lines:?}");
assert_eq!(
lines[1], "1",
"expected exactly one LLM call; lines: {lines:?}"
);
assert_eq!(
lines[2], "false",
"control run should not record an audit reminder; lines: {lines:?}"
);
assert_eq!(
lines[3], "0",
"control run should report zero loop_exit deliveries; lines: {lines:?}"
);
}
fn steer_pipeline(session_id: &str, push_steer_mid_turn: bool) -> String {
let push_line = if push_steer_mid_turn {
format!(
r#" agent_session_push_user_message(
"{session_id}",
{{content: "actually use auth_v2.go", mode: "steer"}},
)"#
)
} else {
String::new()
};
format!(
r#"
import {{ agent_session_push_user_message }} from "std/agent/state"
pipeline main(task) {{
clear_tool_hooks()
let registry = tool_registry()
let tools = tool_define(
registry,
"would_force_push",
"Test stand-in for an irreversible side-effect tool.",
{{parameters: {{}}, handler: {{ _args -> return "would have force-pushed" }}}},
)
let iteration_state = shared_cell({{scope: "task_group", key: "steer-iter-{session_id}", initial: 0}})
let call_counter = shared_cell({{scope: "task_group", key: "steer-calls-{session_id}", initial: 0}})
let mock_llm = {{ _call ->
let csnap = shared_snapshot(call_counter)
shared_cas(call_counter, csnap, csnap.value + 1)
let snap = shared_snapshot(iteration_state)
let n = snap.value
shared_cas(iteration_state, snap, n + 1)
if n == 0 {{
{push_line}
return {{
ok: true,
value: {{
text: "",
tool_calls: [{{id: "call_1", name: "would_force_push", arguments: {{}}}}],
provider: "mock",
model: "mock",
}},
}}
}}
return {{
ok: true,
value: {{text: "acknowledged ##DONE##", tool_calls: [], provider: "mock", model: "mock"}},
}}
}}
let result = agent_loop(
"do the push",
nil,
{{
provider: "mock",
tools: tools,
tool_format: "native",
max_iterations: 4,
loop_until_done: true,
session_id: "{session_id}",
llm_caller: mock_llm,
}},
)
log(result.status)
log(shared_get(call_counter))
let stats = transcript_stats(result.transcript)
log(stats.tool_result_message_count)
let checkpoints = transcript_events_by_kind(result.transcript, "loop_checkpoint")
var mid_turn_deliveries = 0
var loop_exit_deliveries = 0
for event in checkpoints {{
let delivered = event?.metadata?.delivered ?? 0
if delivered >= 1 {{
if event?.metadata?.kind == "loop_exit" {{
loop_exit_deliveries = loop_exit_deliveries + 1
}} else {{
mid_turn_deliveries = mid_turn_deliveries + 1
}}
}}
}}
log(mid_turn_deliveries)
log(loop_exit_deliveries)
// Walk the transcript messages IN ORDER to prove chronological splice:
// the steer user message must land after the tool_result and before the
// final assistant message.
let messages = transcript_messages(result.transcript)
var steer_user_count = 0
var tool_result_idx = -1
var steer_idx = -1
var last_assistant_idx = -1
var idx = 0
for message in messages {{
let role = message?.role ?? ""
let content = message?.content ?? ""
if (role == "tool_result" || role == "tool") && tool_result_idx == -1 {{
tool_result_idx = idx
}}
if role == "user" && content == "actually use auth_v2.go" {{
steer_user_count = steer_user_count + 1
if steer_idx == -1 {{
steer_idx = idx
}}
}}
if role == "assistant" {{
last_assistant_idx = idx
}}
idx = idx + 1
}}
log(steer_user_count)
if tool_result_idx >= 0 && steer_idx > tool_result_idx && last_assistant_idx > steer_idx {{
log("ok")
}} else {{
log("${{tool_result_idx}}/${{steer_idx}}/${{last_assistant_idx}}")
}}
}}
"#
)
}
#[test]
fn steer_user_message_delivered_mid_turn_at_tool_boundary() {
let raw = run_with_bridge(&steer_pipeline("steer-mid-turn", true)).expect("script must run");
let lines = out_lines(&raw);
assert_eq!(lines[0], "done", "lines: {lines:?}");
assert_eq!(lines[1], "2", "expected two LLM calls; lines: {lines:?}");
assert_eq!(
lines[2], "1",
"expected one tool dispatch; lines: {lines:?}"
);
assert!(
lines[3].parse::<i64>().unwrap_or(0) >= 1,
"expected >= 1 mid-turn delivery at a tool boundary; lines: {lines:?}"
);
assert_eq!(
lines[4], "0",
"steer must NOT be delivered at loop_exit; lines: {lines:?}"
);
assert_eq!(
lines[5], "1",
"expected exactly one steer user message in the transcript; lines: {lines:?}"
);
assert_eq!(
lines[6], "ok",
"steer user message must sit chronologically after the tool_result \
and before the final assistant message (verdict is \
tool_result_idx/steer_idx/last_assistant_idx on failure); lines: {lines:?}"
);
}
#[test]
fn steer_control_run_without_inject_is_eval_safe() {
let raw = run_with_bridge(&steer_pipeline("steer-control", false)).expect("script must run");
let lines = out_lines(&raw);
assert_eq!(lines[0], "done", "lines: {lines:?}");
assert_eq!(
lines[1], "2",
"control must make the same two LLM calls as the steer variant; lines: {lines:?}"
);
assert_eq!(
lines[2], "1",
"control must dispatch the tool exactly once, same as the steer variant; lines: {lines:?}"
);
assert_eq!(
lines[3], "0",
"control run should report zero mid-turn deliveries; lines: {lines:?}"
);
assert_eq!(
lines[4], "0",
"control run should report zero loop_exit deliveries; lines: {lines:?}"
);
assert_eq!(
lines[5], "0",
"control run should not record a steer user message; lines: {lines:?}"
);
assert_ne!(
lines[6], "ok",
"control run has no steer message to order; lines: {lines:?}"
);
}