#[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
}
#[allow(dead_code)]
#[path = "../src/check/json.rs"]
mod json;
use json::J;
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};
const QUERY: &str = "Verify an artifact handoff when a recipient sees an old file or the wrong revision after delivery";
const REBUILD: &str = "Locate or rebuild the expected producer artifact before publishing.";
const PUBLISH: &str = "Publish the verified producer artifact to the intended destination.";
const TRACE: &str = "Trace the recipient's selected version or read path.";
const REPORT: &str = "Report the verified recipient read and its revision.";
const REQUESTED: &[u8] = b"reviewed artifact\x00revision-42\xff";
const STALE: &[u8] = b"reviewed artifact\x00revision-41\xff";
struct Sandbox(PathBuf);
impl Sandbox {
fn new(label: &str) -> Self {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let path = std::env::temp_dir().join(format!(
"instinct-case-{label}-{}-{nonce}",
std::process::id()
));
fs::create_dir(&path).unwrap();
let sandbox = Self(path);
let result = sandbox.run(
&[
"bank",
"--from",
"builtin:verify-handoff",
"--project",
"handoff",
],
None,
);
assert!(result.starts_with("banked "), "{result}");
sandbox
}
fn run(&self, args: &[&str], input: Option<&str>) -> String {
let out = self.output(args, input);
assert!(
out.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8(out.stdout).unwrap()
}
fn output(&self, args: &[&str], input: Option<&str>) -> std::process::Output {
let mut cmd = Command::new(env!("CARGO_BIN_EXE_instinct"));
for (key, _) in std::env::vars_os() {
if key.to_string_lossy().starts_with("INSTINCT_") {
cmd.env_remove(key);
}
}
cmd.args(args)
.current_dir(&self.0)
.env("INSTINCT_STORE", self.0.join("bank.hxdb"))
.env("INSTINCT_TEAM", "0")
.env("INSTINCT_STARTER", "0")
.stdout(Stdio::piped())
.stderr(Stdio::piped());
cmd.stdin(if input.is_some() {
Stdio::piped()
} else {
Stdio::null()
});
let mut child = cmd.spawn().unwrap();
if let Some(text) = input {
child.stdin.take().unwrap().write_all(text.as_bytes()).ok();
}
child.wait_with_output().unwrap()
}
}
impl Drop for Sandbox {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn field<'a>(object: &'a J, name: &str) -> &'a J {
let J::Obj(fields) = object else {
panic!("expected object, got {object:?}")
};
&fields
.iter()
.find(|(k, _)| k == name)
.unwrap_or_else(|| panic!("missing {name} in {object:?}"))
.1
}
fn string<'a>(object: &'a J, name: &str) -> &'a str {
match field(object, name) {
J::Str(s) => s,
other => panic!("expected text at {name}, got {other:?}"),
}
}
fn experiences(packet: &J) -> &[J] {
match field(packet, "experiences") {
J::Arr(rows) => rows,
other => panic!("expected experiences array, got {other:?}"),
}
}
fn only_lesson(packet: &J) -> &J {
let [lesson] = experiences(packet) else {
panic!("expected exactly one lesson: {packet:?}")
};
lesson
}
fn recipient_read(dir: &Path) -> Vec<u8> {
let selection = fs::read_to_string(dir.join("selected-version")).unwrap();
fs::read(dir.join(selection)).unwrap()
}
fn observe(dir: &Path, key: &str) -> bool {
let bytes = match key {
"producer_matches" => fs::read(dir.join("producer.bin")).unwrap(),
"destination_matches" => fs::read(dir.join("destination.bin")).unwrap(),
"recipient_matches" => recipient_read(dir),
key => panic!("unexpected handoff question {key}"),
};
bytes == REQUESTED
}
fn next_action(sandbox: &Sandbox, dir: &Path) -> String {
let mut facts = BTreeMap::<String, bool>::new();
for _ in 0..=3 {
let mut args = vec!["decide", "--q", QUERY, "--project", "handoff"];
let encoded = format!(
"{{{}}}",
facts
.iter()
.map(|(k, v)| format!("\"{k}\":{v}"))
.collect::<Vec<_>>()
.join(",")
);
if !facts.is_empty() {
args.extend(["--facts", encoded.as_str()]);
}
let out = sandbox.run(&args, None);
let packet = json::parse(out.as_bytes()).unwrap();
let [lesson] = experiences(&packet) else {
panic!("expected one scoped lesson: {out}")
};
let advice = field(lesson, "case_advice");
match string(advice, "status") {
"ask" => {
let key = string(advice, "key");
assert!(!facts.contains_key(key), "repeated check {key}: {out}");
facts.insert(key.into(), observe(dir, key));
}
"candidate_action" => {
let action = string(advice, "candidate_action");
if action == REPORT {
assert_eq!(
facts.get("recipient_matches"),
Some(&true),
"reported delivery without a fresh recipient read: {out}"
);
}
return action.into();
}
status => panic!("handoff decision returned {status}: {out}"),
}
}
panic!("all three checks answered without an action")
}
fn fixture_succeeds(sandbox: &Sandbox, mask: u8) {
let dir = sandbox.0.join(format!("handoff-{mask}"));
fs::create_dir(&dir).unwrap();
let (producer, destination, recipient) = (mask & 4 != 0, mask & 2 != 0, mask & 1 != 0);
for (name, matches) in [
("producer.bin", producer),
("destination.bin", destination),
("cached.bin", recipient),
] {
fs::write(dir.join(name), if matches { REQUESTED } else { STALE }).unwrap();
}
fs::write(dir.join("selected-version"), "cached.bin").unwrap();
let mut expected = Vec::new();
if !recipient {
if !destination {
if !producer {
expected.push(REBUILD);
}
expected.push(PUBLISH);
}
expected.push(TRACE);
}
expected.push(REPORT);
for recommendation in expected {
let action = next_action(sandbox, &dir);
assert_eq!(
action, recommendation,
"wrong next action for initial fixture {mask:03b}"
);
match action.as_str() {
REBUILD => fs::write(dir.join("producer.bin"), REQUESTED).unwrap(),
PUBLISH => {
fs::copy(dir.join("producer.bin"), dir.join("destination.bin")).unwrap();
}
TRACE => fs::write(dir.join("selected-version"), "destination.bin").unwrap(),
REPORT => assert_eq!(
recipient_read(&dir),
REQUESTED,
"stale bytes reported complete in fixture {mask:03b}"
),
other => panic!("unknown handoff action {other}"),
}
}
assert_eq!(
recipient_read(&dir),
REQUESTED,
"recipient mismatch in fixture {mask:03b}"
);
}
#[test]
fn shipped_handoff_recovers_the_requested_bytes_in_all_eight_initial_states() {
let sandbox = Sandbox::new("eight");
for mask in 0..8 {
fixture_succeeds(&sandbox, mask);
}
}
#[test]
fn ordinary_recall_and_prompt_give_the_first_check_only_in_the_right_project() {
let sandbox = Sandbox::new("scope");
let out = sandbox.run(&["decide", "--project", "handoff", "--q", QUERY], None);
let packet = json::parse(out.as_bytes()).unwrap();
let [lesson] = experiences(&packet) else {
panic!("expected one scoped lesson: {out}")
};
let advice = field(lesson, "case_advice");
assert_eq!(string(advice, "status"), "ask");
let question = string(advice, "question");
let key = string(advice, "key");
assert_eq!(key, "recipient_matches");
let prompt = format!("{{\"prompt\":\"{QUERY}\",\"session_id\":\"case-learning-scope\"}}");
for project in ["unrelated", "handoff"] {
let recall = sandbox.run(&["recall", "--project", project, "--q", QUERY], None);
let hook = sandbox.run(
&["prompt", "--format", "text", "--project", project],
Some(&prompt),
);
for text in [recall, hook] {
if project == "handoff" {
assert!(
text.contains(question) && text.contains(key),
"missing initial check: {text}"
);
} else {
assert!(
text.trim().is_empty(),
"unexpected cross-project advice: {text}"
);
}
}
}
let guide = sandbox.run(
&["guide", "start", "--project", "handoff", "--q", QUERY],
None,
);
assert!(
guide.contains(question) && guide.contains(key),
"guide missed the initial check: {guide}"
);
let outside = sandbox.run(
&["guide", "start", "--project", "unrelated", "--q", QUERY],
None,
);
assert!(
!outside.contains(question),
"guide leaked the initial check: {outside}"
);
let unrelated = sandbox.run(&["decide", "--project", "unrelated", "--q", QUERY], None);
assert!(experiences(&json::parse(unrelated.as_bytes()).unwrap()).is_empty());
}
#[test]
fn lexical_miss_uses_two_observed_facts_only_for_a_unique_scoped_casebook() {
let sandbox = Sandbox::new("fact-match");
let nonsense = "zorpel xyltrium kwezzit";
let facts = r#"{"recipient_matches":false,"destination_matches":false}"#;
let resolve = |project: &str, observed: &str| {
let out = sandbox.run(
&[
"decide",
"--q",
nonsense,
"--project",
project,
"--facts",
observed,
],
None,
);
json::parse(out.as_bytes()).unwrap()
};
assert!(experiences(&resolve("handoff", "{}")).is_empty());
assert!(experiences(&resolve("handoff", r#"{"recipient_matches":false}"#)).is_empty());
assert!(experiences(&resolve("other-project", facts)).is_empty());
let matched = resolve("handoff", facts);
let lesson = only_lesson(&matched);
assert_eq!(
string(field(lesson, "case_advice"), "key"),
"producer_matches"
);
let alternate = include_str!("../skills/instinct/references/verify-handoff.json").replacen(
"Verify delivery at the recipient",
"Verify a second delivery method",
1,
);
let result = sandbox.run(
&["bank", "--from", "-", "--project", "handoff"],
Some(&alternate),
);
assert!(
result.starts_with("banked ") && !result.contains(string(lesson, "id")),
"{result}"
);
assert!(
experiences(&resolve("handoff", facts)).is_empty(),
"ambiguous evidence selected a casebook"
);
let empty_store = sandbox.0.join("empty.hxdb");
for cmd in ["decide", "recall"] {
let bad = sandbox.output(
&[
cmd,
"--q",
nonsense,
"--project",
"handoff",
"--store",
empty_store.to_str().unwrap(),
"--facts",
r#"{"a":"true"}"#,
],
None,
);
assert!(
!bad.status.success() && String::from_utf8_lossy(&bad.stderr).contains("Boolean"),
"{cmd}: {bad:?}"
);
}
}
fn mcp_call(seq: usize, tool: &str, args: &str) -> String {
format!(
r#"{{"jsonrpc":"2.0","id":{seq},"method":"tools/call","params":{{"name":"{tool}","arguments":{args}}}}}"#
)
}
fn tool_text(line: &str, seq: usize) -> String {
let reply = json::parse(line.as_bytes()).unwrap();
assert_eq!(field(&reply, "id"), &J::Num(seq.to_string()));
let result = field(&reply, "result");
assert_eq!(field(result, "isError"), &J::Bool(false), "{line}");
let J::Arr(parts) = field(result, "content") else {
panic!("invalid tool content: {line}")
};
string(&parts[0], "text").into()
}
#[test]
fn observed_mcp_miss_updates_live_recall_and_retries_once_per_outcome() {
let sandbox = Sandbox::new("case-feedback");
let dir = &sandbox.0;
fs::write(dir.join("producer.bin"), REQUESTED).unwrap();
fs::write(dir.join("destination.bin"), STALE).unwrap();
fs::write(dir.join("cached.bin"), STALE).unwrap();
fs::write(dir.join("archive.bin"), REQUESTED).unwrap();
fs::write(dir.join("selected-version"), "cached.bin").unwrap();
let facts = format!(
r#"{{"producer_matches":{},"destination_matches":{},"recipient_matches":{}}}"#,
observe(dir, "producer_matches"),
observe(dir, "destination_matches"),
observe(dir, "recipient_matches")
);
let decide = || {
json::parse(
sandbox
.run(
&[
"decide",
"--q",
QUERY,
"--project",
"handoff",
"--facts",
&facts,
],
None,
)
.as_bytes(),
)
.unwrap()
};
let before = decide();
let lesson = only_lesson(&before);
let id = string(lesson, "id");
assert_eq!(
string(field(lesson, "case_advice"), "candidate_action"),
PUBLISH
);
fs::copy(dir.join("producer.bin"), dir.join("destination.bin")).unwrap();
assert_eq!(recipient_read(dir), STALE);
assert_eq!(fs::read(dir.join("archive.bin")).unwrap(), REQUESTED);
fs::copy(dir.join("archive.bin"), dir.join("cached.bin")).unwrap();
assert_eq!(recipient_read(dir), REQUESTED);
let actual = "Restore the confirmed archived revision into the recipient cache.";
let outcome = "observed-local-archive";
let feedback = format!(
r#"{{"id":"{id}","project":"handoff","paid_off":false,"outcome_id":"{outcome}","note":"Recipient stayed stale after publish; restoring its cache returned the requested bytes.","case":{{"facts":{facts},"action":"{actual}"}}}}"#
);
let recall = format!(r#"{{"project":"handoff","q":"{QUERY}","facts":{facts}}}"#);
let requests = [
mcp_call(1, "instinct_recall", &recall),
mcp_call(2, "instinct_feedback", &feedback),
mcp_call(3, "instinct_recall", &recall),
mcp_call(4, "instinct_feedback", &feedback),
mcp_call(5, "instinct_recall", &recall),
]
.join("\n")
+ "\n";
let output = sandbox.run(&["mcp"], Some(&requests));
let replies: Vec<_> = output
.lines()
.enumerate()
.map(|(i, line)| tool_text(line, i + 1))
.collect();
let [prior, saved, after, retry, again] = replies.as_slice() else {
panic!("unexpected MCP replies: {output}")
};
assert!(prior.contains(PUBLISH), "{prior}");
assert!(saved.contains("miss and observation recorded"), "{saved}");
assert!(retry.contains("already recorded"), "{retry}");
let cli_recall = sandbox.run(
&[
"recall",
"--project",
"handoff",
"--q",
QUERY,
"--facts",
&facts,
],
None,
);
for response in [after, again, &cli_recall] {
assert!(
response.contains("different actions for identical facts")
&& response.contains(outcome),
"{response}"
);
}
let packet = decide();
let lesson = only_lesson(&packet);
assert_eq!(field(lesson, "misses"), &J::Num("1".into()));
assert_eq!(field(lesson, "hits"), &J::Num("0".into()));
let advice = field(lesson, "case_advice");
assert_eq!(string(advice, "status"), "conflict");
assert_eq!(field(advice, "distinct_cases"), &J::Num("2".into()));
assert_eq!(
field(advice, "conflicting_refs"),
&J::Arr(vec![
J::Str("file-handoff-5".into()),
J::Str(outcome.into())
])
);
assert_eq!(
field(advice, "actions"),
&J::Arr(vec![J::Str(PUBLISH.into()), J::Str(actual.into())])
);
}