#[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::{eligibility, parse_json, recall_methods, Json};
use std::path::PathBuf;
const MODES: &[(&str, &str)] = &[
("start", "Choose a first move"),
("options", "Compare available methods"),
("challenge", "Find what could invalidate a method"),
("explain", "Inspect the evidence behind a choice"),
("rehearse", "See which lessons survive a changed brief"),
("transfer", "Design a test in a different setting"),
("verify", "Compare an expectation with an observation"),
("retry", "Recover one check after a correction"),
("handoff", "Prepare a compact card for another agent"),
("debrief", "Draft feedback after an attempt"),
];
fn field<'a>(v: &'a Json, key: &str) -> &'a str {
v.get(key).and_then(Json::as_str).unwrap_or("")
}
fn scenarios() -> Result<Vec<Json>, String> {
match parse_json(include_str!("../skills/instinct/references/scenarios.json"))? {
Json::Arr(rows) => Ok(rows),
_ => Err("invalid built-in scenarios".into()),
}
}
fn obj(fields: Vec<(&str, Json)>) -> Json {
Json::Obj(
fields
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
)
}
fn txt(value: &str) -> Json {
Json::Str(value.into())
}
fn live(path: &PathBuf, q: &str, scope: &eligibility::Scope) -> Result<Vec<Json>, String> {
let matches = recall_methods(path, q, 3, scope)?;
Ok(matches
.iter()
.map(|d| {
let mut card = vec![
("id", txt(&d.id)),
("when", txt(&d.when)),
("method", txt(&d.how)),
("observed", txt(&d.found)),
("evidence", txt(&d.evidence)),
("exception", txt(&d.reconsider)),
("proven", Json::Bool(d.proven_in_use())),
(
"scope",
obj(vec![
("project", txt(&d.meta.project)),
("persona", txt(&d.meta.persona)),
("machine", txt(&d.meta.machine)),
("harness", txt(&d.meta.harness)),
("harness_version", txt(&d.meta.version)),
]),
),
("hits", Json::Num(d.hits.into())),
("misses", Json::Num(d.misses.into())),
];
if let Some(book) = d.casebook.as_ref().filter(|_| d.standing.is_none()) {
card.push(("case_check", txt(&book.first_guidance())));
}
obj(card)
})
.collect())
}
fn sample_cards(case: &Json, changed: bool) -> Vec<Json> {
let methods: &[&str] = if changed {
&["adapt"]
} else {
&["move", "alternative"]
};
methods
.iter()
.map(|k| {
obj(vec![
("id", txt(k)),
(
"when",
txt(field(case, if changed { "changed" } else { "task" })),
),
("method", txt(field(case, k))),
(
"exception",
txt(if changed {
""
} else {
field(case, "exception")
}),
),
("evidence", txt("Illustrative example")),
("observed", Json::Null),
("proven", Json::Bool(false)),
("hits", Json::Num(0.0)),
("misses", Json::Num(0.0)),
])
})
.collect()
}
fn experiment(
path: &std::path::PathBuf,
request: &Json,
scope: &eligibility::Scope,
) -> Result<Json, String> {
let Json::Obj(fields) = request else {
return Err("experiment expects an object".into());
};
let mut seen = std::collections::BTreeSet::new();
for (key, value) in fields {
if !seen.insert(key) {
return Err(format!("duplicate experiment field {key}"));
}
match key.as_str() {
"facts" | "pool" => (),
"mode" | "id" | "after_ref" | "project" | "persona" | "harness" | "harness_version"
| "machine"
if value.as_str().is_some() =>
{
()
}
_ => return Err(format!("unexpected or invalid experiment field {key}")),
}
}
let id = field(request, "id");
if id.trim().is_empty() {
return Err("guide experiment requires a lesson id".into());
}
let missing = "no eligible personal casebook for this id and scope";
let lesson = super::load_user_scoped(path, scope, super::now_secs())?
.into_iter()
.find(|d| d.id == id)
.ok_or(missing)?;
if lesson.meta.source != "banked"
|| lesson.standing.is_some()
|| eligibility::quiet(lesson.hits, lesson.misses)
|| super::quiet_ids(path).contains(id)
{
return Err(missing.into());
}
let book = lesson.casebook.as_ref().ok_or(missing)?;
let mut result = super::case_experiment::experiment(
book,
request.get("facts"),
request.get("pool"),
request.get("after_ref").and_then(Json::as_str),
)?;
if let Json::Obj(fields) = &mut result {
fields.push(("mode".into(), txt("experiment")));
fields.push(("lesson_id".into(), txt(id)));
}
Ok(result)
}
pub(super) fn run(
bank: impl Fn() -> Result<PathBuf, String>,
request: &Json,
scope: &eligibility::Scope,
) -> Result<Json, String> {
let mut cache = std::collections::HashMap::new();
let mode = field(request, "mode");
if mode == "experiment" {
return experiment(&bank()?, request, scope);
}
if ["pool", "facts", "id", "after_ref"]
.iter()
.any(|key| request.get(key).is_some())
{
return Err("id, facts and pool require guide experiment".into());
}
if mode != "run" && request.get("steps").is_some() {
return Err("--steps requires guide run".into());
}
let recipe = match mode {
"prepare" => "start,options,challenge",
"investigate" => "explain,rehearse,transfer",
"review" => "verify,debrief,handoff",
"run" => field(request, "steps"),
_ => return one(&bank, request, scope, &mut cache),
};
let steps: Vec<_> = recipe.split(',').map(str::trim).collect();
let mut seen = std::collections::HashSet::new();
if steps.len() > MODES.len()
|| steps
.iter()
.any(|s| !MODES.iter().any(|(m, _)| m == s) || !seen.insert(*s))
{
return Err("select one to ten distinct workflow names from guide list".into());
}
let Json::Obj(fields) = request else {
return Err("expected guide request".into());
};
let mut reports = Vec::new();
for step in steps {
let mut inputs: Vec<_> = fields
.iter()
.filter(|(k, _)| k != "steps" && k != "mode")
.cloned()
.collect();
inputs.push(("mode".into(), txt(step)));
reports.push(one(&bank, &Json::Obj(inputs), scope, &mut cache)?);
}
Ok(obj(vec![
("mode", txt(mode)),
("reports", Json::Arr(reports)),
]))
}
fn one(
bank: &impl Fn() -> Result<PathBuf, String>,
request: &Json,
scope: &eligibility::Scope,
cache: &mut std::collections::HashMap<String, Vec<Json>>,
) -> Result<Json, String> {
let fields = match request {
Json::Obj(fields) => fields,
_ => return Err("supply a guide request object".into()),
};
for (key, value) in fields {
if !matches!(value, Json::Str(_)) {
return Err(format!("guide field {key} must be a string"));
}
}
let mode = field(request, "mode");
if mode.is_empty() || mode == "list" {
let modes = MODES
.iter()
.map(|(name, purpose)| obj(vec![("name", txt(name)), ("purpose", txt(purpose))]))
.collect();
let examples = scenarios()?.iter().map(|v| txt(field(v, "name"))).collect();
return Ok(obj(vec![
("modes", Json::Arr(modes)),
("examples", Json::Arr(examples)),
(
"experiment",
txt("Choose a teaching case for one banked lesson with two observed actions"),
),
(
"recipes",
Json::Arr(
["prepare", "investigate", "review"]
.iter()
.map(|s| txt(s))
.collect(),
),
),
]));
}
if !MODES.iter().any(|(m, _)| *m == mode) {
return Err(format!("unknown workflow {mode}. Use guide list"));
}
let example = field(request, "example");
let sample = if example.is_empty() {
None
} else {
if [
"q",
"changed",
"expected",
"observed",
"correction",
"method",
"test",
"prediction",
"exception",
]
.iter()
.any(|k| request.get(k).is_some())
{
return Err("use either an example or your own inputs".into());
}
Some(
scenarios()?
.into_iter()
.find(|row| field(row, "name") == example)
.ok_or("unknown example. Use guide list")?,
)
};
let input = |key| {
sample
.as_ref()
.and_then(|row| {
row.get(match key {
"q" => "task",
"method" => "move",
"test" => "adapt",
other => other,
})
})
.or_else(|| request.get(key))
.and_then(Json::as_str)
};
let q = input("q")
.filter(|s| !s.trim().is_empty())
.ok_or("guide requires a task via --q or --example")?;
let changed = input("changed").unwrap_or("");
if matches!(mode, "rehearse" | "transfer")
&& (changed.trim().is_empty() || changed.trim() == q.trim())
{
return Err("supply a different target situation via --changed".into());
}
let mut facts = Vec::new();
let mut lines = Vec::new();
let mut status = "ready";
let mut lookup = |task: &str, changed: bool| match &sample {
Some(row) => Ok(sample_cards(row, changed)),
None => {
if let Some(cards) = cache.get(task) {
return Ok::<_, String>(cards.clone());
}
let cards = live(&bank()?, task, scope)?;
cache.insert(task.into(), cards.clone());
Ok(cards)
}
};
if matches!(mode, "verify" | "debrief") {
let expected = input("expected").ok_or("supply the expected result via --expected")?;
facts.push(("expected", txt(expected)));
if let Some(actual) = input("observed") {
facts.push(("observed", txt(actual)));
status = if expected == actual {
"match"
} else {
"mismatch"
};
lines.push(format!("Expected {expected:?}; observed {actual:?}."));
if mode == "debrief" {
lines.push(
if expected == actual {
"Record a hit only if the method contributed to this result."
} else {
"Identify which assumption failed before attributing a miss to the method."
}
.into(),
);
if let Some(method) = input("method").filter(|s| !s.trim().is_empty()) {
facts.push((
"lesson_draft",
obj(vec![
("when", txt(q)),
("method_tried", txt(method)),
("expected", txt(expected)),
("observed", txt(actual)),
("reconsider_if", input("exception").map_or(Json::Null, txt)),
]),
));
lines.push(format!("Method tried: {method}"));
} else {
lines.push("Add the method you tried to draft a reusable lesson.".into());
}
facts.push(("feedback_recorded", Json::Bool(false)));
}
} else {
status = "awaiting_observation";
lines.push(format!(
"Collect a current result to compare with {expected:?}."
));
}
} else if mode == "retry" {
let correction = if sample.is_some() {
"That's still wrong."
} else {
input("correction")
.filter(|s| !s.trim().is_empty())
.ok_or("supply the current user correction via --correction")?
};
let packet = match &sample {
Some(row) => Some(obj(vec![("check", txt(field(row, "check")))])),
None => {
let raw = super::premortem(&bank()?, correction, Some(q), scope)?;
if raw.is_empty() {
None
} else {
Some(parse_json(&raw)?)
}
}
};
if let Some(p) = packet {
lines.push(field(&p, "check").into());
facts.push(("check", p));
} else {
status = "abstained";
lines.push("No single proven check fits this correction.".into());
}
} else {
let cards = lookup(q, false)?;
let first = cards.first();
if first.is_none() {
status = "no_lesson";
}
match mode {
"start" => {
if let Some(c) = first {
lines.push(
c.get("case_check")
.and_then(Json::as_str)
.unwrap_or(field(c, "method"))
.into(),
);
facts.push(("choice", c.clone()));
if c.get("proven") != Some(&Json::Bool(true)) {
lines.push("Try this as a candidate and check the result.".into());
}
} else {
lines.push("Start with the smallest observable result the user needs.".into());
}
}
"options" => {
let mut seen = std::collections::HashSet::new();
let choices: Vec<_> = cards
.iter()
.filter(|c| seen.insert(field(c, "method")))
.cloned()
.collect();
for c in &choices {
lines.push(format!(
"{} — applies when {}",
field(c, "method"),
field(c, "when")
));
}
if choices.is_empty() {
lines.push("No banked methods fit this brief.".into());
}
facts.push(("options", Json::Arr(choices)));
}
"challenge" => {
let boundaries: Vec<_> = cards
.iter()
.filter(|c| !field(c, "exception").is_empty())
.map(|c| {
obj(vec![
("id", txt(field(c, "id"))),
("method", txt(field(c, "method"))),
("exception", txt(field(c, "exception"))),
])
})
.collect();
for b in &boundaries {
lines.push(format!(
"{} Reconsider if this applies: {}",
field(b, "method"),
field(b, "exception")
));
}
if boundaries.is_empty() {
status = "missing_boundary";
lines.push(
"Identify one observation that would make you abandon the proposed method."
.into(),
);
}
facts.push(("boundaries", Json::Arr(boundaries)));
}
"explain" => {
if let Some(c) = first {
lines.push(format!("{} — {}", field(c, "method"), field(c, "evidence")));
if let Some(obs) = c.get("observed").and_then(Json::as_str) {
lines.push(format!("Previously observed: {obs}"));
}
facts.push(("evidence_card", c.clone()));
} else {
lines.push("No scoped evidence supports a banked method for this task.".into());
}
}
"rehearse" | "transfer" => {
let next = lookup(changed, true)?;
facts.push(("target", txt(changed)));
if mode == "rehearse" {
status = "compared";
for (label, a, b) in [
("retained", &cards, &next),
("dropped", &cards, &next),
("introduced", &next, &cards),
] {
let subset: Vec<_> = a
.iter()
.filter(|c| {
b.iter().any(|d| field(c, "id") == field(d, "id"))
== (label == "retained")
})
.cloned()
.collect();
lines.push(format!(
"{label}: {}",
if subset.is_empty() {
"none".into()
} else {
subset
.iter()
.map(|c| field(c, "method"))
.collect::<Vec<_>>()
.join(" / ")
}
));
facts.push((label, Json::Arr(subset)));
}
} else {
status = if first.is_some() {
"hypothesis"
} else {
"no_source_lesson"
};
if let Some(c) = first {
facts.push(("source_lesson", c.clone()));
lines.push(format!(
"Test whether this move transfers: {}",
field(c, "method")
));
}
else {
lines.push("Find a source case with an observed outcome before proposing a transfer.".into());
}
if let Some(check) = first
.and_then(|c| c.get("case_check"))
.and_then(Json::as_str)
{
lines.push(check.into());
}
lines.push(format!("Target task: {changed}"));
if input("prediction").is_none() {
lines.push("Name a prediction that could turn out wrong.".into());
}
if let Some(test) = input("test") {
facts.push(("test", txt(test)));
lines.push(format!("Test: {test}"));
}
if let Some(prediction) = input("prediction") {
facts.push(("prediction", txt(prediction)));
lines.push(format!("Prediction: {prediction}"));
}
if let Some(c) = first {
let known = next.iter().any(|d| field(d, "id") == field(c, "id"));
facts.push(("source_also_retrieved_for_target", Json::Bool(known)));
facts.push(("hypothesis",txt(&format!("Applying '{}' to '{}' may reproduce the relevant part of the earlier outcome.",field(c,"method"),changed))));
if !field(c, "exception").is_empty() {
lines.push(format!(
"Check the source boundary: {}",
field(c, "exception")
));
}
}
facts.push(("target_lessons", Json::Arr(next)));
}
}
"handoff" => {
lines.push(format!("Task: {q}"));
if let Some(c) = first {
lines.push(format!("Try: {}", field(c, "method")));
lines.push(format!("Prior evidence: {}", field(c, "evidence")));
if !field(c, "exception").is_empty() {
lines.push(format!("Reconsider if: {}", field(c, "exception")));
}
facts.push(("lesson_id", txt(field(c, "id"))));
if let Some(scope) = c.get("scope") {
facts.push(("scope", scope.clone()));
}
if c.get("proven") != Some(&Json::Bool(true)) {
lines.push("Treat this method as a candidate.".into());
}
}
else {
lines.push("No prior method selected.".into());
}
if let (Some(expected), Some(observed)) = (input("expected"), input("observed")) {
let state = if expected == observed {
"match"
} else {
"mismatch"
};
facts.push((
"current_comparison",
obj(vec![
("status", txt(state)),
("expected", txt(expected)),
("observed", txt(observed)),
]),
));
lines.push(format!(
"Current observation: expected {expected:?}; observed {observed:?}."
));
if expected != observed {
lines.push(
"Still open: resolve the discrepancy and repeat the check.".into(),
);
}
} else {
lines.push("Still open: verify the current outcome.".into());
}
}
_ => unreachable!(),
}
}
Ok(obj(vec![
("mode", txt(mode)),
("task", txt(q)),
(
"source",
txt(if sample.is_some() { "example" } else { "live" }),
),
("status", txt(status)),
(
"steps",
Json::Arr(lines.into_iter().map(Json::Str).collect()),
),
("details", obj(facts)),
]))
}
pub(super) fn display(packet: &Json) -> String {
if field(packet, "mode") == "experiment" {
return super::json_out(packet);
}
if let Some(Json::Arr(reports)) = packet.get("reports") {
return reports.iter().map(display).collect::<Vec<_>>().join("\n\n");
}
if let Some(Json::Arr(modes)) = packet.get("modes") {
let mut rows: Vec<_> = modes
.iter()
.map(|m| format!("{:10} {}", field(m, "name"), field(m, "purpose")))
.collect();
if let Some(Json::Arr(names)) = packet.get("examples") {
rows.push(format!(
"Examples: {}",
names
.iter()
.filter_map(Json::as_str)
.collect::<Vec<_>>()
.join(", ")
));
}
rows.push("experiment Choose a teaching case for a two-action lesson with --id ID".into());
rows.push("Recipes: prepare, investigate, review. Choose your own with guide run --steps start,challenge,handoff".into());
rows.push("Try: instinct guide challenge --example shared-document".into());
return rows.join("\n");
}
let mut lines = vec![format!(
"{} · {} · {}",
field(packet, "mode"),
field(packet, "source"),
field(packet, "status")
)];
if field(packet, "source") == "example" && field(packet, "mode") != "handoff" {
lines.push(field(packet, "task").into());
}
if let Some(Json::Arr(steps)) = packet.get("steps") {
lines.extend(steps.iter().filter_map(Json::as_str).map(str::to_string));
}
lines.join("\n")
}
pub(super) fn book() -> Result<String, String> {
let scope = eligibility::env_scope();
let no_bank = || Err("the guidebook cannot read a bank".to_string());
let mut data = match run(no_bank, &obj(vec![]), &scope)? {
Json::Obj(fields) => fields,
_ => unreachable!(),
};
let mut examples = Vec::new();
for row in scenarios()? {
let name = field(&row, "name");
let mut modes = Vec::new();
for (mode, _) in MODES {
let report = run(
no_bank,
&obj(vec![("mode", txt(mode)), ("example", txt(name))]),
&scope,
)?;
modes.push((mode.to_string(), report));
}
examples.push((name.to_string(), Json::Obj(modes)));
}
data.push(("reports".into(), Json::Obj(examples)));
let data = super::json_out(&Json::Obj(data))
.replace('<', "\\u003c")
.replace('>', "\\u003e")
.replace('&', "\\u0026");
Ok(include_str!("guidebook.html").replacen("__GUIDE_DATA__", &data, 1))
}