#[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::super::{
append, eligibility, journal, json_out, load_plain, now_secs, parse_json, scope_identity,
Discovery, Json,
};
use super::{digest, json, observe};
use std::path::PathBuf;
use std::io::Read;
fn text<'a>(v: &'a Json, key: &str) -> &'a str {
v.get(key).and_then(Json::as_str).unwrap_or("")
}
fn s(v: impl Into<String>) -> Json {
Json::Str(v.into())
}
fn object(v: Vec<(&str, Json)>) -> Json {
Json::Obj(v.into_iter().map(|(k, v)| (k.into(), v)).collect())
}
fn hash(v: &Json) -> String {
digest::hex(&digest::sha256(json_out(v).as_bytes()))
}
fn scope(d: &Discovery) -> Json {
let names = ["project", "persona", "harness", "version", "machine"];
object(
names
.into_iter()
.zip(scope_identity(&d.meta))
.filter(|(_, v)| !v.is_empty())
.map(|(k, v)| (k, s(v)))
.collect(),
)
}
pub(crate) fn fingerprint(d: &Discovery) -> String {
hash(&object(vec![
("domain", s("instinct.lesson-check-binding/v1")),
("id", s(&d.id)),
("title", s(&d.title)),
("when", s(&d.when)),
("found", s(&d.found)),
("how", s(&d.how)),
("evidence", s(&d.evidence)),
("reconsider", s(&d.reconsider)),
("tags", s(&d.tags)),
("scope", scope(d)),
("source", s(&d.meta.source)),
("valid_until", s(d.meta.valid_until.to_string())),
]))
}
fn sidecar(path: &PathBuf) -> PathBuf {
let mut p = path.as_os_str().to_owned();
p.push(".capabilities.hxdb");
PathBuf::from(p)
}
fn bank_binding(path: &PathBuf) -> Result<String, String> {
let canonical =
std::fs::canonicalize(path).map_err(|_| "cannot resolve bank binding; nothing recorded")?;
let mut bytes = b"instinct.bank-location/v1\0".to_vec();
bytes.extend_from_slice(canonical.as_os_str().as_encoded_bytes());
Ok(digest::hex(&digest::sha256(&bytes)))
}
fn binding_refusal(path: &PathBuf, id: &str) -> String {
let quote = |v: &str| format!("'{}'", v.replace('\'', "'\\''"));
format!("bank binding differs or is missing; nothing recorded. Reattach with an explicitly approved policy on stdin: instinct check attach --lesson {} --store {} --input -", quote(id), quote(&path.to_string_lossy()))
}
fn strict(bytes: &[u8]) -> Result<Json, String> {
json::parse(bytes)?;
parse_json(std::str::from_utf8(bytes).map_err(|_| "invalid UTF-8")?)
}
fn canonical(v: &Json) -> Json {
match v {
Json::Obj(o) => {
let mut o: Vec<_> = o.iter().map(|(k, v)| (k.clone(), canonical(v))).collect();
o.sort_by(|a, b| a.0.cmp(&b.0));
Json::Obj(o)
}
Json::Arr(a) => Json::Arr(a.iter().map(canonical).collect()),
other => other.clone(),
}
}
fn canonical_policy(mut p: Json) -> Json {
if let Json::Obj(o) = &mut p {
for (k, v) in o.iter_mut() {
if matches!(k.as_str(), "allowed" | "required") {
if let Json::Arr(a) = v {
a.sort_by(|x, y| x.as_str().cmp(&y.as_str()));
}
}
}
}
canonical(&p)
}
fn lesson(path: &PathBuf, id: &str) -> Result<Discovery, String> {
load_plain(path)?
.into_iter()
.find(|d| d.id == id)
.ok_or_else(|| "unknown active lesson".into())
}
fn valid_policy(raw: &[u8], d: &Discovery) -> Result<Json, String> {
let p = strict(raw)?;
let mut validation = p.clone();
if let Json::Obj(o) = &mut validation {
o.retain(|(k, _)| k != "assumptions");
o.push((
"assumptions".into(),
object(vec![("trusted_quiescent_staging", Json::Bool(false))]),
));
}
let root = if cfg!(windows) { "C:\\" } else { "/" };
let (out, error) = observe::observe(root, json_out(&validation).as_bytes());
if error {
return Err(format!(
"invalid attached policy: {}",
text(&parse_json(&out)?, "reason")
));
}
let expected = canonical(&scope(d));
let actual = canonical(p.get("scope").unwrap_or(&Json::Obj(vec![])));
if actual != expected {
return Err("attached policy scope must exactly match lesson scope".into());
}
if let Some(a) = p.get("assumptions") {
match a {
Json::Obj(o)
if o.len() <= 1
&& o.iter().all(|(k, v)| {
k == "trusted_quiescent_staging" && matches!(v, Json::Bool(_))
}) => {}
_ => return Err("invalid policy assumptions".into()),
}
}
Ok(canonical_policy(p))
}
fn attachment(path: &PathBuf, id: &str) -> Result<Option<Json>, String> {
let p = sidecar(path);
if !p.exists() {
return Ok(None);
}
let mut found = None;
for line in journal::read(&p)?.lines().filter(|l| !l.trim().is_empty()) {
let v = strict(line.as_bytes())?;
if !matches!(
text(&v, "schema"),
"instinct.check-attachment/v1" | "instinct.check-revocation/v1"
) {
return Err("unsupported attachment record".into());
}
if text(&v, "schema") == "instinct.check-revocation/v1" {
validate_revocation(&v)?;
}
if text(&v, "lesson_id") == id {
found = Some(v)
}
}
Ok(found)
}
fn validate_revocation(v: &Json) -> Result<(), String> {
let Json::Obj(fields) = v else {
return Err("invalid revocation record".into());
};
let keys = ["schema", "bank_binding", "lesson_id", "revision"];
let binding = text(v, "bank_binding");
let revision = v.get("revision").and_then(Json::as_f64).unwrap_or(0.0);
if fields.len() != keys.len()
|| fields.iter().any(|(k, _)| !keys.contains(&k.as_str()))
|| text(v, "lesson_id").is_empty()
|| binding.len() != 64
|| !binding
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|| !revision.is_finite()
|| revision < 1.0
|| revision.fract() != 0.0
|| revision > 2147483647.0
{
return Err("invalid revocation record".into());
}
Ok(())
}
fn next_revision(previous: Option<&Json>) -> Result<u64, String> {
let Some(previous) = previous else {
return Ok(1);
};
let n = previous
.get("revision")
.and_then(Json::as_f64)
.ok_or("attachment revision missing")?;
if !n.is_finite() || n < 1.0 || n.fract() != 0.0 || n >= 2147483647.0 {
return Err("attachment revision invalid or exhausted".into());
}
Ok(n as u64 + 1)
}
pub fn detach_cli(args: &[String]) -> Result<String, String> {
let mut opts = std::collections::BTreeMap::new();
let mut i = 0;
while i < args.len() {
let k = args[i].as_str();
if !matches!(k, "--lesson" | "--store") || opts.contains_key(k) {
return Err("usage: check detach --lesson ID --store BANK".into());
}
i += 1;
let v = args.get(i).ok_or("missing detach option value")?;
if v.trim().is_empty() {
return Err("empty detach option".into());
}
opts.insert(k, v.as_str());
i += 1;
}
let id = *opts.get("--lesson").ok_or("detach requires --lesson")?;
let path = PathBuf::from(
opts.get("--store")
.ok_or("detach requires explicit --store")?,
);
let _bank = journal::identity_lock(&path)?;
let _ = lesson(&path, id)?;
let Some(previous) = attachment(&path, id)? else {
return Ok(format!("no check attached to {id}"));
};
let binding = bank_binding(&path)?;
if text(&previous, "bank_binding") != binding {
return Err(binding_refusal(&path, id));
}
if text(&previous, "schema") == "instinct.check-revocation/v1" {
return Ok(format!("check already detached from {id}"));
}
let revision = next_revision(Some(&previous))?;
let event = object(vec![
("schema", s("instinct.check-revocation/v1")),
("bank_binding", s(binding)),
("lesson_id", s(id)),
("revision", Json::Num(revision as f64)),
]);
let p = sidecar(&path);
let _side = journal::identity_lock(&p)?;
append(&p, &json_out(&event))?;
Ok(format!("check detached from {id}"))
}
pub fn attach_cli(args: &[String]) -> Result<String, String> {
let mut opts = std::collections::BTreeMap::new();
let mut i = 0;
while i < args.len() {
let k = args[i].as_str();
if !matches!(k, "--lesson" | "--store" | "--input") || opts.contains_key(k) {
return Err("usage: check attach --lesson ID --store BANK --input FILE|-".into());
}
i += 1;
let v = args.get(i).ok_or("missing attach option value")?;
if v.is_empty() {
return Err("empty attach option".into());
}
opts.insert(k, v.as_str());
i += 1;
}
let id = *opts.get("--lesson").ok_or("attach requires --lesson")?;
let path = PathBuf::from(
opts.get("--store")
.ok_or("attach requires explicit --store")?,
);
let input = *opts.get("--input").ok_or("attach requires --input")?;
let mut raw = Vec::new();
if input == "-" {
std::io::stdin()
.lock()
.take((json::MAX_BYTES + 1) as u64)
.read_to_end(&mut raw)
.map_err(|_| "cannot read attachment input")?;
} else {
std::fs::File::open(input)
.map_err(|_| "cannot open attachment input")?
.take((json::MAX_BYTES + 1) as u64)
.read_to_end(&mut raw)
.map_err(|_| "cannot read attachment input")?;
}
let _bank = journal::identity_lock(&path)?;
let d = lesson(&path, id)?;
let policy = valid_policy(&raw, &d)?;
let fp = fingerprint(&d);
let ph = hash(&policy);
let binding = bank_binding(&path)?;
let previous = attachment(&path, id)?;
if previous.as_ref().is_some_and(|a| {
text(a, "schema") == "instinct.check-attachment/v1"
&& text(a, "bank_binding") == binding
&& text(a, "lesson_fingerprint") == fp
&& text(a, "policy_sha256") == ph
}) {
return Ok(format!("check already attached to {id}"));
}
let revision = next_revision(previous.as_ref())?;
let event = object(vec![
("schema", s("instinct.check-attachment/v1")),
("bank_binding", s(binding)),
("lesson_id", s(id)),
("lesson_fingerprint", s(fp)),
("policy_sha256", s(ph)),
("revision", Json::Num(revision as f64)),
("policy", policy),
]);
let p = sidecar(&path);
let _side = journal::identity_lock(&p)?;
append(&p, &json_out(&event))?;
Ok(format!("check attached to {id}"))
}
#[cfg(test)]
mod lifecycle_tests {
use super::*;
#[test]
fn revocation_shape_rejects_malformed_and_unknown_fields() {
let good = object(vec![
("schema", s("instinct.check-revocation/v1")),
("bank_binding", s("a".repeat(64))),
("lesson_id", s("in-test")),
("revision", Json::Num(2.0)),
]);
assert!(validate_revocation(&good).is_ok());
for (key, bad) in [
("revision", Json::Num(0.0)),
("revision", Json::Num(1.5)),
("revision", Json::Num(2147483648.0)),
("bank_binding", s("wrong")),
("lesson_id", s("")),
] {
let mut v = good.clone();
if let Json::Obj(fields) = &mut v {
*fields.iter_mut().find(|(k, _)| k == key).unwrap() = (key.into(), bad);
}
assert!(validate_revocation(&v).is_err());
}
let mut extra = good.clone();
if let Json::Obj(fields) = &mut extra {
fields.push(("ignored".into(), Json::Bool(true)));
}
assert!(validate_revocation(&extra).is_err());
}
#[test]
fn revision_limits_never_wrap_or_round() {
assert_eq!(next_revision(None).unwrap(), 1);
for n in [0.0, -1.0, 1.5, 2147483647.0, f64::INFINITY] {
assert!(next_revision(Some(&object(vec![("revision", Json::Num(n))]))).is_err());
}
assert_eq!(
next_revision(Some(&object(vec![("revision", Json::Num(2147483646.0))]))).unwrap(),
2147483647
);
}
}
fn verification_digest(v: &Json) -> String {
if let Json::Obj(o) = v {
hash(&canonical(&Json::Obj(
o.iter()
.filter(|(k, _)| k != "receipt_sha256")
.cloned()
.collect(),
)))
} else {
String::new()
}
}
pub(crate) fn metadata(v: &Json, id: &str, key: &str) -> Option<String> {
let Json::Obj(o) = v else { return None };
let keys = [
"schema",
"adapter",
"lesson_id",
"lesson_fingerprint",
"policy_sha256",
"check_revision",
"scope",
"observation_key",
"observation_sha256",
"root_sha256",
"authorization",
"evidence_origin",
"trusted_quiescent_staging",
"receipt_sha256",
];
if o.len() != keys.len() || o.iter().any(|(k, _)| !keys.contains(&k.as_str())) {
return None;
}
if text(v, "schema") != "instinct.check-verification/v1"
|| text(v, "adapter") != "artifact-inventory/v1"
|| text(v, "lesson_id") != id
|| key.is_empty()
|| text(v, "observation_key") != key
|| text(v, "authorization") != "not_evaluated"
|| text(v, "evidence_origin") != "adapter_observed"
|| v.get("trusted_quiescent_staging") != Some(&Json::Bool(true))
{
return None;
}
for k in [
"lesson_fingerprint",
"policy_sha256",
"observation_sha256",
"root_sha256",
"receipt_sha256",
] {
let h = text(v, k);
if h.len() != 64
|| !h
.bytes()
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
{
return None;
}
}
let r = v.get("check_revision")?.as_f64()?;
if !r.is_finite() || r < 1.0 || r.fract() != 0.0 || r > 2147483647.0 {
return None;
}
if !matches!(v.get("scope"), Some(Json::Obj(_)))
|| text(v, "receipt_sha256") != verification_digest(v)
{
return None;
}
Some(text(v, "lesson_fingerprint").to_owned())
}
pub(crate) fn hit(
path: &PathBuf,
id: &str,
note: &str,
key: &str,
root: &str,
trusted: bool,
) -> Result<String, String> {
if cfg!(not(unix)) {
return Err(
"check-verified hits are not supported on this platform; nothing recorded".into(),
);
}
if !trusted || root.is_empty() || key.trim().is_empty() {
return Err(
"checked hit requires root, trusted-staging and nonempty outcome-id; nothing recorded"
.into(),
);
}
let key = key.trim();
let _lock = journal::identity_lock(path)?;
let d = lesson(path, id)?;
eligibility::scope_check(&d.meta, &eligibility::env_scope(), now_secs())
.map_err(|r| format!("check scope refused: {r}"))?;
let a = attachment(path, id)?.ok_or("lesson has no attached check; nothing recorded")?;
if text(&a, "bank_binding") != bank_binding(path)? {
return Err(binding_refusal(path, id));
}
if text(&a, "schema") == "instinct.check-revocation/v1" {
return Err("check attachment was revoked; explicitly reattach before verification; nothing recorded".into());
}
let fp = fingerprint(&d);
if text(&a, "lesson_fingerprint") != fp {
return Err("lesson changed since check attachment; reattach before verification".into());
}
if let Some(prior) = d.outcomes.get(key) {
if *prior != Some(true) {
return Err("outcome already has a conflicting verdict; nothing recorded".into());
}
return Ok(format!("outcome already recorded for {id}"));
}
let policy = a.get("policy").ok_or("attachment policy missing")?;
if hash(policy) != text(&a, "policy_sha256") {
return Err("attachment fingerprint mismatch".into());
}
let mut p = policy.clone();
if let Json::Obj(o) = &mut p {
o.retain(|(k, _)| k != "assumptions");
o.push((
"assumptions".into(),
object(vec![("trusted_quiescent_staging", Json::Bool(true))]),
));
}
let (out, error) = observe::observe(root, json_out(&p).as_bytes());
if error {
return Err(format!(
"check error; nothing recorded: {}",
text(&parse_json(&out)?, "reason")
));
}
let obs = parse_json(&out)?;
let Some(Json::Arr(checks)) = obs.get("checks") else {
return Err("check produced no predicates; nothing recorded".into());
};
if text(&obs, "validity") != "observed_snapshot"
|| checks.is_empty()
|| checks
.iter()
.any(|c| c.get("result").map(|r| text(r, "verdict")) != Some("pass"))
{
return Err("observed check did not pass; nothing recorded".into());
}
let mut proof = object(vec![
("schema", s("instinct.check-verification/v1")),
("adapter", s("artifact-inventory/v1")),
("lesson_id", s(id)),
("lesson_fingerprint", s(fp)),
("policy_sha256", s(text(&a, "policy_sha256"))),
(
"check_revision",
a.get("revision")
.cloned()
.ok_or("attachment revision missing")?,
),
("scope", scope(&d)),
("observation_key", s(key)),
("observation_sha256", s(hash(&canonical(&obs)))),
(
"root_sha256",
s(digest::hex(&digest::sha256(root.as_bytes()))),
),
("authorization", s("not_evaluated")),
("evidence_origin", s("adapter_observed")),
("trusted_quiescent_staging", Json::Bool(true)),
]);
let proof_hash = verification_digest(&proof);
if let Json::Obj(o) = &mut proof {
o.push(("receipt_sha256".into(), s(proof_hash)));
}
let event = object(vec![
("kind", s("hit")),
("id", s(id)),
("ts", Json::Num(now_secs() as f64)),
("note", s(note)),
("outcome_id", s(key)),
("check_verification", proof),
]);
append(path, &json_out(&event))?;
Ok(format!("check-verified hit recorded for {id}"))
}
pub(crate) fn provenance(event: &Json, d: &Discovery) -> (u8, String) {
match event.get("check_verification") {
None => (0, String::new()),
Some(v) => match metadata(v, &d.id, text(event, "outcome_id")) {
Some(fp) => (1, fp),
None => (3, String::new()),
},
}
}
pub(crate) fn annotate_eval(
path: &PathBuf,
mut output: String,
json_mode: bool,
since: Option<u64>,
) -> Result<String, String> {
let raw = journal::read(path)?;
let marker = raw
.lines()
.filter_map(|l| parse_json(l).ok())
.any(|v| v.get("check_verification").is_some());
if !marker {
return Ok(output);
}
let mut total = 0u64;
let mut verified = 0u64;
let mut downgraded = 0u64;
let mut invalid = 0u64;
for line in raw.lines().filter(|l| !l.trim().is_empty()) {
let v = parse_json(line)?;
if let Some(meta) = v.get("check_verification") {
let ts = v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64;
if since.is_none_or(|f| ts >= f)
&& metadata(meta, text(&v, "id"), text(&v, "outcome_id")).is_none()
{
invalid += 1;
}
}
}
super::super::fold_bank_verified(path, |_, ts, hit, state| {
if hit && since.is_none_or(|f| ts >= f) {
total += 1;
if state == 1 {
verified += 1;
} else if state == 2 {
downgraded += 1;
}
}
})?;
let summary = object(vec![
("schema", s("instinct.verified-feedback-summary/v1")),
("claimed_hits", Json::Num((total - verified) as f64)),
("check_verified_hits", Json::Num(verified as f64)),
("downgraded_hits", Json::Num(downgraded as f64)),
("invalid_records", Json::Num(invalid as f64)),
]);
if json_mode {
let mut v = parse_json(&output)?;
if let Json::Obj(o) = &mut v {
o.push(("verification".into(), summary));
}
output = json_out(&v);
} else {
output.push_str(&format!("\n\nVerification: {verified} check-verified hits, {} claimed hits; {downgraded} downgraded, {invalid} invalid records.\nA check verifies its predicate under stated assumptions, not causation or authorization.",total-verified));
}
Ok(output)
}