#[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 std::{
collections::{BTreeMap, HashMap},
fs,
io::{Read, Write},
path::{Path, PathBuf},
};
use super::{eligibility::Meta, rehearsal::StandingInstruction, Discovery};
pub(super) fn enabled() -> bool {
std::env::var("INSTINCT_INDEX").map_or(true, |v| v != "0")
}
fn feed(h: &mut [u64; 4], blocks: &[u8]) {
for c in blocks.chunks_exact(32) {
for j in 0..4 {
let w = u64::from_le_bytes([
c[j * 8],
c[j * 8 + 1],
c[j * 8 + 2],
c[j * 8 + 3],
c[j * 8 + 4],
c[j * 8 + 5],
c[j * 8 + 6],
c[j * 8 + 7],
]);
h[j] = (h[j].rotate_left(5) ^ w).wrapping_mul(0x517CC1B727220A95);
}
}
}
fn seed() -> [u64; 4] {
[
0x9E3779B97F4A7C15,
0xC2B2AE3D27D4EB4F,
0x165667B19E3779F9,
0x27D4EB2F165667C5,
]
}
fn finish(mut h: [u64; 4], tail: &[u8], total: u64) -> (u64, u64) {
let mut block = [0u8; 32];
block[..tail.len()].copy_from_slice(tail);
feed(&mut h, &block);
h[0] ^= total;
let mut a = (h[0] ^ h[1].rotate_left(17)).wrapping_mul(0xFF51AFD7ED558CCD);
let mut b = (h[2] ^ h[3].rotate_left(23)).wrapping_mul(0xC4CEB9FE1A85EC53);
a ^= a >> 32;
b ^= b >> 29;
(a, b)
}
fn mix(bytes: &[u8]) -> (u64, u64) {
let mut h = seed();
let whole = bytes.len() - bytes.len() % 32;
feed(&mut h, &bytes[..whole]);
finish(h, &bytes[whole..], bytes.len() as u64)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) struct Key {
len: u64,
a: u64,
b: u64,
weights: [u8; 4],
}
pub(super) fn key(path: &Path) -> Option<Key> {
if !enabled() {
return None;
}
let mut file = fs::File::open(path).ok()?;
let mut buf = vec![0u8; 65536];
let mut h = seed();
let mut total = 0u64;
let mut tail: Vec<u8> = Vec::new();
for _ in 0..u64::MAX {
let mut got = 0usize;
for _ in 0..buf.len() {
if got == buf.len() {
break;
}
let n = file.read(&mut buf[got..]).ok()?;
if n == 0 {
break;
}
got += n;
}
let whole = got - got % 32;
feed(&mut h, &buf[..whole]);
total += got as u64;
if got < buf.len() {
tail = buf[whole..got].to_vec();
break;
}
}
let (a, b) = finish(h, &tail, total);
let (w, t, body) = super::lex_weights();
Some(Key {
len: total,
a,
b,
weights: [
w as u8,
t as u8,
body as u8,
super::concepts::enabled() as u8,
],
})
}
fn idx_path(path: &Path) -> PathBuf {
let mut s = path.as_os_str().to_owned();
s.push(".idx");
PathBuf::from(s)
}
fn put_u32(o: &mut Vec<u8>, v: u32) {
o.extend_from_slice(&v.to_le_bytes())
}
fn put_u64(o: &mut Vec<u8>, v: u64) {
o.extend_from_slice(&v.to_le_bytes())
}
fn put_str(o: &mut Vec<u8>, s: &str) {
put_u32(o, s.len() as u32);
o.extend_from_slice(s.as_bytes())
}
fn header(key: &Key) -> Vec<u8> {
let mut o = b"INSTIDX1".to_vec();
put_str(&mut o, env!("CARGO_PKG_VERSION"));
put_u64(&mut o, key.len);
put_u64(&mut o, key.a);
put_u64(&mut o, key.b);
o.extend_from_slice(&key.weights);
o
}
fn put_entry(o: &mut Vec<u8>, d: &Discovery) {
let at = o.len();
put_u32(o, 0);
for s in [
&d.meta.source,
&d.meta.state,
&d.meta.evidence_status,
&d.meta.project,
&d.meta.persona,
&d.meta.harness,
&d.meta.version,
&d.meta.machine,
] {
put_str(o, s);
}
put_u64(o, d.meta.valid_until);
for s in [
&d.id,
&d.title,
&d.when,
&d.found,
&d.how,
&d.evidence,
&d.reconsider,
&d.tags,
] {
put_str(o, s);
}
put_u64(o, d.ts);
put_u32(o, d.hits);
put_u32(o, d.misses);
put_u32(o, d.embedding.len() as u32);
for f in &d.embedding {
put_u32(o, f.to_bits());
}
if let Some(s) = &d.standing {
o.push(1);
put_str(o, &s.text);
put_str(o, &s.reference);
} else {
o.push(0);
}
let len = (o.len() - at - 4) as u32;
o[at..at + 4].copy_from_slice(&len.to_le_bytes());
}
fn encode(key: &Key, all: &[Discovery]) -> Vec<u8> {
let mut o = header(key);
put_u32(&mut o, all.len() as u32);
for d in all {
put_entry(&mut o, d);
}
let mut lens: Vec<u32> = Vec::with_capacity(all.len());
let mut vocab: BTreeMap<String, Vec<(u32, u32)>> = BTreeMap::new();
for (i, d) in all.iter().enumerate() {
let words = super::tokens(&d.lex_text());
lens.push(words.len() as u32);
let mut counts: HashMap<String, u32> = HashMap::new();
for w in words {
*counts.entry(w).or_insert(0) += 1;
}
for (w, tf) in counts {
vocab.entry(w).or_default().push((i as u32, tf));
}
}
for l in &lens {
put_u32(&mut o, *l);
}
let mut blob: Vec<u8> = Vec::new();
let mut voff: Vec<u32> = vec![0];
let mut poff: Vec<u32> = vec![0];
let mut pdoc: Vec<u32> = Vec::new();
let mut ptf: Vec<u32> = Vec::new();
for (w, list) in &vocab {
blob.extend_from_slice(w.as_bytes());
voff.push(blob.len() as u32);
for &(doc, tf) in list {
pdoc.push(doc);
ptf.push(tf);
}
poff.push(pdoc.len() as u32);
}
put_u32(&mut o, vocab.len() as u32);
for v in &voff {
put_u32(&mut o, *v);
}
o.extend_from_slice(&blob);
for v in poff.iter().chain(pdoc.iter()).chain(ptf.iter()) {
put_u32(&mut o, *v);
}
let mut per: Vec<Vec<String>> = Vec::with_capacity(all.len());
let mut avocab: BTreeMap<String, u32> = BTreeMap::new();
for d in all {
let mut seen = super::anchors(&d.when);
seen.extend(super::anchors(&d.title));
for t in d.tags.split(';') {
seen.extend(super::anchors(t));
}
let mut v: Vec<String> = seen.into_iter().collect();
v.sort();
for a in &v {
avocab.entry(a.clone()).or_insert(0);
}
per.push(v);
}
let idmap: HashMap<&str, u32> = avocab
.keys()
.enumerate()
.map(|(i, s)| (s.as_str(), i as u32))
.collect();
put_u32(&mut o, avocab.len() as u32);
let mut ablob: Vec<u8> = Vec::new();
let mut aoff: Vec<u32> = vec![0];
for s in avocab.keys() {
ablob.extend_from_slice(s.as_bytes());
aoff.push(ablob.len() as u32);
}
for v in &aoff {
put_u32(&mut o, *v);
}
o.extend_from_slice(&ablob);
let mut aloff: Vec<u32> = vec![0];
let mut aids: Vec<u32> = Vec::new();
for v in &per {
for a in v {
aids.push(idmap[a.as_str()]);
}
aloff.push(aids.len() as u32);
}
for v in aloff.iter().chain(aids.iter()) {
put_u32(&mut o, *v);
}
let (a, b) = mix(&o);
put_u64(&mut o, a);
put_u64(&mut o, b);
o
}
fn check(buf: &[u8], key: &Key) -> Option<usize> {
let n = buf.len().checked_sub(16)?;
let (a, b) = mix(&buf[..n]);
if buf[n..n + 8] != a.to_le_bytes() || buf[n + 8..] != b.to_le_bytes() {
return None;
}
let h = header(key);
if buf.get(..h.len()) != Some(&h[..]) {
return None;
}
Some(n)
}
pub(super) fn store(path: &Path, key: &Key, all: &[Discovery]) {
if !enabled() {
return;
}
let target = idx_path(path);
if fs::read(&target)
.ok()
.is_some_and(|b| check(&b, key).is_some())
{
return;
}
if key_now(path) != Some(*key) {
return;
}
let bytes = encode(key, all);
let mut tmp = target.as_os_str().to_owned();
tmp.push(format!(".tmp{}", std::process::id()));
let tmp = PathBuf::from(tmp);
let ok = super::journal::private_options()
.create(true)
.truncate(true)
.write(true)
.open(&tmp)
.and_then(|mut f| f.write_all(&bytes))
.and_then(|_| fs::rename(&tmp, &target))
.is_ok();
if !ok {
let _ = fs::remove_file(&tmp);
}
}
fn key_now(path: &Path) -> Option<Key> {
key(path)
}
struct Rd<'a> {
b: &'a [u8],
o: usize,
}
fn take<'a>(r: &mut Rd<'a>, n: usize) -> Option<&'a [u8]> {
let e = r.o.checked_add(n)?;
let s = r.b.get(r.o..e)?;
r.o = e;
Some(s)
}
fn r_u32(r: &mut Rd) -> Option<u32> {
let s = take(r, 4)?;
Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
fn r_u64(r: &mut Rd) -> Option<u64> {
let s = take(r, 8)?;
Some(u64::from_le_bytes([
s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7],
]))
}
fn r_str(r: &mut Rd) -> Option<String> {
let n = r_u32(r)? as usize;
String::from_utf8(take(r, n)?.to_vec()).ok()
}
fn r_meta(r: &mut Rd) -> Option<Meta> {
let source = r_str(r)?;
let state = r_str(r)?;
let evidence_status = r_str(r)?;
let project = r_str(r)?;
let persona = r_str(r)?;
let harness = r_str(r)?;
let version = r_str(r)?;
let machine = r_str(r)?;
let valid_until = r_u64(r)?;
Some(Meta {
source,
state,
evidence_status,
project,
persona,
harness,
version,
machine,
valid_until,
})
}
fn r_rest(r: &mut Rd, meta: Meta) -> Option<Discovery> {
let id = r_str(r)?;
let title = r_str(r)?;
let when = r_str(r)?;
let found = r_str(r)?;
let how = r_str(r)?;
let evidence = r_str(r)?;
let reconsider = r_str(r)?;
let tags = r_str(r)?;
let ts = r_u64(r)?;
let hits = r_u32(r)?;
let misses = r_u32(r)?;
let dims = r_u32(r)? as usize;
let raw = take(r, dims.checked_mul(4)?)?;
let embedding: Vec<f32> = raw
.chunks_exact(4)
.map(|c| f32::from_bits(u32::from_le_bytes([c[0], c[1], c[2], c[3]])))
.collect();
let standing = if take(r, 1)?[0] == 1 {
Some(StandingInstruction {
text: r_str(r)?,
reference: r_str(r)?,
})
} else {
None
};
Some(Discovery {
id,
ts,
title,
when,
found,
how,
evidence,
reconsider,
tags,
embedding,
hits,
misses,
outcomes: HashMap::new(),
standing,
meta,
})
}
pub(super) struct Index {
buf: Vec<u8>,
lens: usize,
vn: usize,
voff: usize,
vblob: usize,
poff: usize,
pdoc: usize,
ptf: usize,
avn: usize,
aoff: usize,
ablob: usize,
aloff: usize,
aids: usize,
}
fn word(buf: &[u8], at: usize) -> usize {
u32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]]) as usize
}
pub(super) fn open(
path: &Path,
key: &Key,
scope: &super::eligibility::Scope,
now: u64,
) -> Option<(Vec<Discovery>, Vec<u32>, Index)> {
if !enabled() {
return None;
}
let buf = fs::read(idx_path(path)).ok()?;
let end = check(&buf, key)?;
let mut r = Rd {
b: &buf[..end],
o: header(key).len(),
};
let n = r_u32(&mut r)? as usize;
if n > end / 64 {
return None;
}
let mut all = Vec::with_capacity(n);
let mut pos = Vec::with_capacity(n);
for _ in 0..n {
let len = r_u32(&mut r)? as usize;
let stop = r.o.checked_add(len)?;
if stop > end {
return None;
}
let meta = r_meta(&mut r)?;
if super::eligibility::scope_check(&meta, scope, now).is_ok() {
pos.push(all.len() as u32);
all.push(r_rest(&mut r, meta)?);
} else {
pos.push(u32::MAX);
r.o = stop;
}
if r.o != stop {
return None;
}
}
let lens = r.o;
take(&mut r, n.checked_mul(4)?)?;
let vn = r_u32(&mut r)? as usize;
let voff = r.o;
take(&mut r, vn.checked_add(1)?.checked_mul(4)?)?;
let blob = word(&buf, voff + vn * 4);
let vblob = r.o;
take(&mut r, blob)?;
let poff = r.o;
take(&mut r, vn.checked_add(1)?.checked_mul(4)?)?;
let total = word(&buf, poff + vn * 4);
let pdoc = r.o;
take(&mut r, total.checked_mul(4)?)?;
let ptf = r.o;
take(&mut r, total.checked_mul(4)?)?;
let avn = r_u32(&mut r)? as usize;
let aoff = r.o;
take(&mut r, avn.checked_add(1)?.checked_mul(4)?)?;
let ablob_len = word(&buf, aoff + avn * 4);
let ablob = r.o;
take(&mut r, ablob_len)?;
let aloff = r.o;
take(&mut r, n.checked_add(1)?.checked_mul(4)?)?;
let atotal = word(&buf, aloff + n * 4);
let aids = r.o;
take(&mut r, atotal.checked_mul(4)?)?;
if r.o != end {
return None;
}
for i in 0..vn {
if word(&buf, voff + i * 4) > word(&buf, voff + i * 4 + 4)
|| word(&buf, voff + i * 4 + 4) > blob
|| word(&buf, poff + i * 4) > word(&buf, poff + i * 4 + 4)
|| word(&buf, poff + i * 4 + 4) > total
{
return None;
}
}
for i in 0..total {
if word(&buf, pdoc + i * 4) >= n {
return None;
}
}
for i in 0..avn {
if word(&buf, aoff + i * 4) > word(&buf, aoff + i * 4 + 4)
|| word(&buf, aoff + i * 4 + 4) > ablob_len
{
return None;
}
}
for i in 0..n {
if word(&buf, aloff + i * 4) > word(&buf, aloff + i * 4 + 4)
|| word(&buf, aloff + i * 4 + 4) > atotal
{
return None;
}
}
for i in 0..atotal {
if word(&buf, aids + i * 4) >= avn {
return None;
}
}
Some((
all,
pos,
Index {
buf,
lens,
vn,
voff,
vblob,
poff,
pdoc,
ptf,
avn,
aoff,
ablob,
aloff,
aids,
},
))
}
pub(super) fn scores(ix: &Index, pos: &[u32], count: usize, query: &str) -> Vec<f32> {
let mut terms = super::tokens(query);
terms.sort();
terms.dedup();
if terms.is_empty() || count == 0 {
return vec![0.0; count];
}
let b = &ix.buf;
let mut total_length = 0usize;
for i in 0..pos.len() {
if pos[i] != u32::MAX {
total_length += word(b, ix.lens + i * 4);
}
}
let n = count as f32;
let avgdl = (total_length as f32 / n).max(1.0);
let mut out = vec![0.0f32; count];
for term in &terms {
let (mut lo, mut hi) = (0usize, ix.vn);
for _ in 0..40 {
if lo >= hi {
break;
}
let mid = (lo + hi) / 2;
let word_at = &b
[ix.vblob + word(b, ix.voff + mid * 4)..ix.vblob + word(b, ix.voff + mid * 4 + 4)];
if word_at < term.as_bytes() {
lo = mid + 1;
} else {
hi = mid;
}
}
if lo >= ix.vn
|| &b[ix.vblob + word(b, ix.voff + lo * 4)..ix.vblob + word(b, ix.voff + lo * 4 + 4)]
!= term.as_bytes()
{
continue;
}
let (from, to) = (word(b, ix.poff + lo * 4), word(b, ix.poff + lo * 4 + 4));
let df = (from..to)
.filter(|&j| pos[word(b, ix.pdoc + j * 4)] != u32::MAX)
.count() as f32;
let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
for j in from..to {
let doc = word(b, ix.pdoc + j * 4);
if pos[doc] != u32::MAX {
let tf = word(b, ix.ptf + j * 4) as f32;
let length = word(b, ix.lens + doc * 4) as f32;
out[pos[doc] as usize] +=
idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * length / avgdl));
}
}
}
out
}
pub(super) fn common_anchors(
ix: &Index,
pos: &[u32],
count: usize,
) -> std::collections::HashSet<String> {
let b = &ix.buf;
let mut df = vec![0usize; ix.avn];
for doc in 0..pos.len() {
if pos[doc] != u32::MAX {
for j in word(b, ix.aloff + doc * 4)..word(b, ix.aloff + doc * 4 + 4) {
df[word(b, ix.aids + j * 4)] += 1;
}
}
}
let mut out = std::collections::HashSet::new();
for (i, c) in df.iter().enumerate() {
if c * 10 > count {
out.insert(
String::from_utf8_lossy(
&b[ix.ablob + word(b, ix.aoff + i * 4)
..ix.ablob + word(b, ix.aoff + i * 4 + 4)],
)
.into_owned(),
);
}
}
out
}