#[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::Json;
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug, PartialEq)]
struct Check {
key: String,
question: String,
cost: f64,
}
#[derive(Clone, Debug, PartialEq)]
struct Example {
truth: u16,
action: String,
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Casebook {
checks: Vec<Check>,
examples: BTreeMap<String, Example>,
}
pub(super) fn obj<const N: usize>(fields: [(&str, Json); N]) -> Json {
Json::Obj(
fields
.into_iter()
.map(|(key, value)| (key.into(), value))
.collect(),
)
}
pub(super) fn strings<'a>(values: impl IntoIterator<Item = &'a str>) -> Json {
Json::Arr(values.into_iter().map(|s| Json::Str(s.into())).collect())
}
fn shape(value: &Json, name: &str, required: &[&str]) -> Result<(), String> {
let Json::Obj(fields) = value else {
return Err(format!("{name} must be an object"));
};
if fields.len() != required.len() || required.iter().any(|k| value.get(k).is_none()) {
return Err(format!(
"{name} requires exactly these fields once each: {}",
required.join(", ")
));
}
Ok(())
}
fn bounded_array<'a>(value: &'a Json, field: &str, limit: usize) -> Result<&'a [Json], String> {
match value.get(field) {
Some(Json::Arr(rows)) if (1..=limit).contains(&rows.len()) => Ok(rows),
_ => Err(format!("{field} must have between 1 and {limit} entries")),
}
}
fn bounded_text<'a>(value: &'a Json, field: &str, limit: usize) -> Result<&'a str, String> {
value.get(field).and_then(Json::as_str)
.filter(|s| !s.is_empty() && s.trim() == *s && s.len() <= limit && !s.chars().any(char::is_control))
.ok_or_else(|| format!("{field} must be nonempty single-line text of at most {limit} bytes without surrounding whitespace"))
}
fn valid_key(key: &str) -> bool {
!key.is_empty()
&& key.len() <= 128
&& key
.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b'-'))
}
pub(super) fn boolean_facts(value: &Json) -> Result<BTreeMap<&str, bool>, String> {
let Json::Obj(fields) = value else {
return Err("facts must be a JSON object".into());
};
if fields.len() > 128 {
return Err("facts accepts at most 128 keys".into());
}
let mut facts = BTreeMap::new();
for (key, value) in fields {
if !valid_key(key) {
return Err(
"fact keys must be 1..128 ASCII letters, digits, dots, underscores or hyphens"
.into(),
);
}
let Json::Bool(b) = value else {
return Err(format!("fact {key} must be a Boolean"));
};
if facts.insert(key.as_str(), *b).is_some() {
return Err(format!("duplicate fact {key}"));
}
}
Ok(facts)
}
pub(super) fn validate_facts(value: &Json) -> Result<(), String> {
boolean_facts(value).map(|_| ())
}
impl Casebook {
pub(super) fn experiment_keys(&self) -> impl ExactSizeIterator<Item = &str> {
self.checks.iter().map(|check| check.key.as_str())
}
pub(super) fn experiment_refs(&self) -> impl Iterator<Item = (&str, u16, &str)> {
self.examples
.iter()
.map(|(reference, row)| (reference.as_str(), row.truth, row.action.as_str()))
}
pub(super) fn parse(value: &Json) -> Result<Self, String> {
shape(value, "casebook", &["checks", "examples"])?;
let mut checks = Vec::new();
for check in bounded_array(value, "checks", 16)? {
shape(check, "check", &["key", "question", "cost"])?;
let key = bounded_text(check, "key", 128)?;
if !valid_key(key) {
return Err(
"check keys accept ASCII letters, digits, dots, underscores and hyphens".into(),
);
}
let question = bounded_text(check, "question", 512)?;
let cost = check
.get("cost")
.and_then(Json::as_f64)
.filter(|n| n.is_finite() && *n >= 1.0 && n.fract() == 0.0)
.ok_or("check cost must be a positive finite integer")?;
checks.push(Check {
key: key.into(),
question: question.into(),
cost,
});
}
checks.sort_by(|a, b| a.key.cmp(&b.key));
if let Some(pair) = checks.windows(2).find(|p| p[0].key == p[1].key) {
return Err(format!("duplicate check {}", pair[0].key));
}
let mut examples = BTreeMap::new();
for row in bounded_array(value, "examples", 128)? {
shape(row, "example", &["ref", "facts", "action"])?;
let reference = bounded_text(row, "ref", 256)?;
let action = bounded_text(row, "action", 512)?;
let facts = boolean_facts(row.get("facts").unwrap())?;
if facts.len() != checks.len() {
return Err(format!(
"example {reference} must have exactly the declared check keys"
));
}
let mut truth = 0u16;
for (idx, check) in checks.iter().enumerate() {
let value = facts
.get(check.key.as_str())
.ok_or_else(|| format!("example {reference} is missing check {}", check.key))?;
truth |= (*value as u16) << idx;
}
if examples
.insert(
reference.into(),
Example {
truth,
action: action.into(),
},
)
.is_some()
{
return Err(format!("duplicate example ref {reference}"));
}
}
Ok(Self { checks, examples })
}
pub(super) fn to_json(&self) -> Json {
let checks = self
.checks
.iter()
.map(|c| {
obj([
("key", Json::Str(c.key.clone())),
("question", Json::Str(c.question.clone())),
("cost", Json::Num(c.cost)), ])
})
.collect();
let examples = self
.examples
.iter()
.map(|(reference, example)| {
let facts = self
.checks
.iter()
.enumerate()
.map(|(i, c)| (c.key.clone(), Json::Bool(example.truth & (1 << i) != 0)))
.collect();
obj([
("ref", Json::Str(reference.clone())),
("facts", Json::Obj(facts)),
("action", Json::Str(example.action.clone())),
])
})
.collect();
obj([
("checks", Json::Arr(checks)),
("examples", Json::Arr(examples)),
])
}
pub(super) fn merge(&self, other: &Self) -> Result<Self, String> {
if self.checks != other.checks {
return Err("casebook checks, questions and costs must agree".into());
}
let mut merged = self.clone();
for (reference, row) in &other.examples {
match merged.examples.get(reference) {
Some(old) if old != row => {
return Err(format!("conflicting example ref {reference}"))
}
Some(_) => (),
None => {
merged.examples.insert(reference.clone(), row.clone());
} }
}
if merged.examples.len() > 128 {
return Err("merged casebook exceeds 128 examples".into());
}
Ok(merged)
}
pub(super) fn advise(&self, facts: &Json) -> Result<Json, String> {
Ok(self.decide(&boolean_facts(facts)?).json())
}
pub(super) fn guidance(&self, facts: &Json) -> Result<String, String> {
Ok(self.decide(&boolean_facts(facts)?).text())
}
pub(super) fn first_guidance(&self) -> String {
self.decide(&BTreeMap::new()).text()
}
fn decide<'a>(&'a self, facts: &BTreeMap<&'a str, bool>) -> Decision<'a> {
let mut observed = 0u16;
let mut truth = 0u16;
let mut ignored = Vec::new();
for (&key, &value) in facts {
match self.checks.binary_search_by(|c| c.key.as_str().cmp(key)) {
Ok(idx) => {
observed |= 1 << idx;
truth |= (value as u16) << idx;
}
Err(_) => ignored.push(key),
}
}
let mut evidence = Decision {
outcome: Outcome::Unseen,
actions: BTreeSet::new(),
refs: Vec::new(),
conflicting_refs: Vec::new(),
distinct: 0,
ignored,
};
if observed == 0 && !facts.is_empty() {
return evidence;
}
let mut signatures = Vec::new();
for (reference, row) in &self.examples {
if row.truth & observed == truth {
evidence.refs.push(reference.as_str());
evidence.actions.insert(row.action.as_str());
signatures.push((row.truth, row.action.as_str()));
}
}
signatures.sort_unstable();
signatures.dedup();
evidence.distinct = signatures.len();
if evidence.actions.len() <= 1 {
if let Some(&action) = evidence.actions.first() {
evidence.outcome = Outcome::Candidate(action);
}
return evidence;
}
let conflicts: BTreeSet<_> = signatures
.windows(2)
.filter(|p| p[0].0 == p[1].0)
.map(|p| p[0].0)
.collect();
signatures.sort_unstable_by_key(|&(_, action)| action);
let mut total_true = [0usize; 16];
let mut same_action_pairs = [0usize; 16];
for group in signatures.chunk_by(|a, b| a.1 == b.1) {
let mut group_true = [0usize; 16];
for &(mut set_bits, _) in group {
while set_bits != 0 {
group_true[set_bits.trailing_zeros() as usize] += 1;
set_bits &= set_bits - 1;
}
}
for (key, &n) in group_true[..self.checks.len()].iter().enumerate() {
total_true[key] += n;
same_action_pairs[key] += n * (group.len() - n);
}
}
let scores: [usize; 16] = std::array::from_fn(|i| {
total_true[i] * (evidence.distinct - total_true[i]) - same_action_pairs[i]
});
evidence.conflicting_refs = self
.examples
.iter()
.filter(|(_, row)| conflicts.contains(&row.truth))
.map(|(r, _)| r.as_str())
.collect();
let best = self
.checks
.iter()
.zip(scores)
.filter(|(_, count)| *count != 0)
.max_by(|(a, ac), (b, bc)| {
separation_score(*ac, b.cost)
.cmp(&separation_score(*bc, a.cost))
.then_with(|| b.cost.total_cmp(&a.cost))
.then_with(|| b.key.cmp(&a.key))
});
evidence.outcome = match best {
Some((check, count)) => Outcome::Ask(check, count),
None => Outcome::Conflict,
};
evidence
}
}
fn separation_score(pairs: usize, opposite_cost: f64) -> (i32, u128) {
let bits = opposite_cost.to_bits();
let significand = (bits & ((1u64 << 52) - 1)) | (1u64 << 52);
let product = (pairs as u128) * u128::from(significand);
let shift = product.leading_zeros();
((bits >> 52) as i32 - shift as i32, product << shift)
}
enum Outcome<'a> {
Ask(&'a Check, usize),
Candidate(&'a str),
Unseen,
Conflict,
}
struct Decision<'a> {
outcome: Outcome<'a>,
actions: BTreeSet<&'a str>,
refs: Vec<&'a str>,
conflicting_refs: Vec<&'a str>,
distinct: usize,
ignored: Vec<&'a str>,
}
impl Decision<'_> {
fn json(&self) -> Json {
let (status, mut extra) = match self.outcome {
Outcome::Ask(c, pairs) => (
"ask",
vec![
("key".into(), Json::Str(c.key.clone())),
("question".into(), Json::Str(c.question.clone())),
("cost".into(), Json::Num(c.cost)),
("separated_pairs".into(), Json::Num(pairs as f64)),
],
),
Outcome::Candidate(action) => (
"candidate_action",
vec![("candidate_action".into(), Json::Str(action.into()))],
),
Outcome::Unseen => ("unseen", vec![]),
Outcome::Conflict => ("conflict", vec![]),
};
let mut fields = vec![
("status".into(), Json::Str(status.into())),
("supporting_refs".into(), strings(self.refs.iter().copied())),
("distinct_cases".into(), Json::Num(self.distinct as f64)),
("actions".into(), strings(self.actions.iter().copied())),
(
"conflicting_refs".into(),
strings(self.conflicting_refs.iter().copied()),
),
("ignored_keys".into(), strings(self.ignored.iter().copied())), ];
fields.append(&mut extra);
Json::Obj(fields)
}
fn text(&self) -> String {
let mut text = match self.outcome {
Outcome::Ask(c, n) => format!("Check {}. {} Its cost is {} and its answer separates {n} {} of cases with different actions.", c.key, c.question, c.cost, if n == 1 { "pair" } else { "pairs" }),
Outcome::Candidate(action) => format!("Candidate action from matching examples is \"{action}\". Verify it in the current situation."),
Outcome::Unseen => "No recorded example matches the supplied facts. Gather evidence before choosing an action.".into(),
Outcome::Conflict => "Matching examples record different actions for identical facts. Review the conflicting examples before choosing an action.".into(),
};
if !self.refs.is_empty() {
let label = if self.distinct == 1 {
"distinct case"
} else {
"distinct cases"
};
text.push_str(&format!(
" Evidence from {} {label} ({}).",
self.distinct,
short_list(&self.refs)
));
}
if !self.conflicting_refs.is_empty() && matches!(self.outcome, Outcome::Ask(_, _)) {
text.push_str(&format!(
" Conflicting examples include {}.",
short_list(&self.conflicting_refs)
));
}
if !self.ignored.is_empty() {
text.push_str(&format!(
" This casebook ignores {}.",
short_list(&self.ignored)
));
}
text
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parse_json;
fn check(key: &str, cost: f64) -> Json {
obj([
("key", Json::Str(key.into())),
("question", Json::Str(format!("Does {key} hold?"))),
("cost", Json::Num(cost)),
])
}
fn row(reference: &str, a: bool, b: bool, action: &str) -> Json {
obj([
("ref", Json::Str(reference.into())),
("facts", obj([("a", Json::Bool(a)), ("b", Json::Bool(b))])),
("action", Json::Str(action.into())),
])
}
fn make_book(cost: f64, examples: Vec<Json>) -> Casebook {
Casebook::parse(&obj([
("checks", Json::Arr(vec![check("b", 1.0), check("a", cost)])),
("examples", Json::Arr(examples)),
]))
.unwrap()
}
fn advise(book: &Casebook, facts: &str) -> Json {
book.advise(&parse_json(facts).unwrap()).unwrap()
}
#[test]
fn chooses_by_conflicting_pairs_per_cost_without_counting_duplicate_observations() {
let rows = vec![
row("one", false, false, "inspect"),
row("two", true, false, "replace"),
row("three", false, true, "replace"),
row("copy", false, true, "replace"),
];
let book = make_book(1.0, rows.clone());
let ask = advise(&book, "{}");
assert_eq!(ask.get("key").and_then(Json::as_str), Some("a"));
assert_eq!(ask.get("separated_pairs"), Some(&Json::Num(1.0)));
assert_eq!(ask.get("distinct_cases"), Some(&Json::Num(3.0)));
assert!(book.first_guidance().contains("Does a hold?"));
let costlier = make_book(2.0, rows);
assert_eq!(
advise(&costlier, "{}").get("key").and_then(Json::as_str),
Some("b")
);
let supported = advise(&book, r#"{"b":true,"other.domain":true}"#);
assert_eq!(
supported.get("candidate_action").and_then(Json::as_str),
Some("replace")
);
assert_eq!(
supported.get("supporting_refs"),
Some(&strings(["copy", "three"]))
);
assert_eq!(
supported.get("ignored_keys"),
Some(&strings(["other.domain"]))
);
assert_eq!(supported.get("distinct_cases"), Some(&Json::Num(1.0)));
assert_eq!(
advise(&book, r#"{"a":true,"b":true}"#)
.get("status")
.and_then(Json::as_str),
Some("unseen")
);
}
#[test]
fn selects_a_costlier_check_when_it_distinguishes_more_pairs_per_unit() {
let rows = [
(false, false, false, "stay"),
(false, false, true, "stay"),
(false, true, false, "stay"),
(true, false, false, "move"),
];
let examples = rows
.into_iter()
.enumerate()
.map(|(i, (a, b, c, action))| {
obj([
("ref", Json::Str(i.to_string())),
(
"facts",
obj([
("a", Json::Bool(a)),
("b", Json::Bool(b)),
("c", Json::Bool(c)),
]),
),
("action", Json::Str(action.into())), ])
})
.collect();
let book = Casebook::parse(&obj([
(
"checks",
Json::Arr(vec![check("a", 2.0), check("b", 1.0), check("c", 1.0)]),
),
("examples", Json::Arr(examples)),
]))
.unwrap();
let choice = advise(&book, "{}");
assert_eq!(choice.get("key").and_then(Json::as_str), Some("a"));
assert_eq!(choice.get("separated_pairs"), Some(&Json::Num(3.0)));
}
#[test]
fn distinguishes_no_recognized_keys_from_empty_facts_and_returns_single_record_support() {
let book = make_book(3.0, vec![row("one", false, true, "inspect")]);
let single = advise(&book, "{}");
assert_eq!(
single.get("status").and_then(Json::as_str),
Some("candidate_action")
);
assert_eq!(single.get("supporting_refs"), Some(&strings(["one"])));
assert_eq!(single.get("distinct_cases"), Some(&Json::Num(1.0)));
let unknown = advise(&book, r#"{"another":false}"#);
assert_eq!(unknown.get("status").and_then(Json::as_str), Some("unseen"));
assert_eq!(unknown.get("supporting_refs"), Some(&strings([])));
assert_eq!(unknown.get("ignored_keys"), Some(&strings(["another"])));
}
#[test]
fn discloses_contradictions_while_a_useful_question_remains_then_abstains() {
let book = make_book(
1.0,
vec![
row("one", false, false, "repair"),
row("two", false, false, "replace"),
row("copy", false, false, "repair"),
row("third", true, false, "inspect"),
],
);
let first = advise(&book, "{}");
assert_eq!(first.get("status").and_then(Json::as_str), Some("ask"));
assert_eq!(
first.get("conflicting_refs"),
Some(&strings(["copy", "one", "two"]))
);
let conflict = advise(&book, r#"{"a":false}"#);
assert_eq!(
conflict.get("status").and_then(Json::as_str),
Some("conflict")
);
assert_eq!(
conflict.get("actions"),
Some(&strings(["repair", "replace"]))
);
assert_eq!(conflict.get("candidate_action"), None);
assert_eq!(conflict.get("distinct_cases"), Some(&Json::Num(2.0)));
}
#[test]
fn canonical_merge_reuses_unchanged_refs_and_rejects_edits_or_overflow() {
let rows = vec![
row("z", true, false, "replace"),
row("a", false, true, "inspect"),
];
let book = make_book(2.0, rows.clone());
let reordered = obj([
("examples", Json::Arr(rows.into_iter().rev().collect())),
("checks", Json::Arr(vec![check("a", 2.0), check("b", 1.0)])),
]);
let canonical = Casebook::parse(&reordered).unwrap();
assert_eq!(book.to_json(), canonical.to_json());
assert_eq!(book.merge(&canonical).unwrap(), book);
let new = make_book(2.0, vec![row("third", false, false, "other")]);
assert_eq!(book.merge(&new).unwrap(), new.merge(&book).unwrap());
assert!(book
.merge(&make_book(2.0, vec![row("z", true, false, "other")]))
.is_err());
assert!(book
.merge(&make_book(5.0, vec![row("z", true, false, "replace")]))
.is_err());
let full = make_book(
2.0,
(0..128)
.map(|i| row(&i.to_string(), false, true, "inspect"))
.collect(),
);
assert!(full.merge(&new).is_err());
}
#[test]
fn validates_shapes_keys_boolean_values_and_costs() {
for invalid in [
r#"{"a":true,"a":false}"#,
r#"{"a":"true"}"#,
r#"{"bad key":false}"#,
"[]",
"false",
] {
assert!(validate_facts(&parse_json(invalid).unwrap()).is_err());
}
assert!(validate_facts(&parse_json("{}").unwrap()).is_ok());
let examples = Json::Arr(vec![row("ref", true, false, "act")]);
for cost in [-1.0, 0.0, 0.5, 1.25, f64::NAN, f64::INFINITY] {
assert!(Casebook::parse(&obj([
("checks", Json::Arr(vec![check("a", cost), check("b", 1.0)])),
("examples", examples.clone())
]))
.is_err());
}
for checks in [
vec![],
vec![check("a", 1.0)],
vec![check("a", 1.0), check("a", 1.0)],
vec![check("x", 1.0), check("b", 1.0)],
] {
assert!(Casebook::parse(&obj([
("checks", Json::Arr(checks)),
("examples", examples.clone())
]))
.is_err());
}
let checks = Json::Arr(vec![check("a", 1.0), check("b", 1.0)]);
let duplicated = Json::Arr(vec![
row("ref", true, false, "act"),
row("ref", true, false, "act"),
]);
assert!(
Casebook::parse(&obj([("checks", checks.clone()), ("examples", duplicated)])).is_err()
);
assert!(Casebook::parse(&obj([
("checks", checks),
("examples", Json::Arr(Vec::new()))
]))
.is_err());
}
#[test]
fn ranks_extreme_integer_costs_without_rounding_or_overflow() {
let large = f64::MAX;
let almost = f64::from_bits(large.to_bits() - 1);
assert!(separation_score(8128, large) > separation_score(8128, almost));
assert_eq!(separation_score(2, 1.0), separation_score(1, 2.0));
assert!(separation_score(1, large) > separation_score(8128, 1.0));
}
}
fn short_list(entries: &[&str]) -> String {
let shown = entries.len().min(3);
let mut text = entries[..shown].join(", ");
if entries.len() > shown {
text.push_str(&format!(" (+{} more)", entries.len() - shown));
}
text
}