# Independent acceptance tests for docs/check-verified-feedback.md (instinct check attach, hit --check, eval, MCP, consolidation fold); every line is literal Rust via TAG.
# Source of truth for tests/check_feedback.rs: regenerate with /tmp/instinct-rc-520fHLXr/hxc export-rust tests/check_feedback.hlx, then rustfmt (1.9)
TAG # #[cfg(unix)]
TAG # mod fb {
TAG # use std::io::Write;
TAG # use std::path::{Path, PathBuf};
TAG # use std::process::{Command, Stdio};
TAG # use std::sync::atomic::{AtomicUsize, Ordering};
TAG # use std::time::Duration;
TAG # fn bin() -> &'static str {
TAG # env!("CARGO_BIN_EXE_instinct")
TAG # }
TAG # // ---------------------------------------------------------------- minimal JSON reader for the outputs
TAG # #[derive(Debug, Clone, PartialEq)]
TAG # enum J {
TAG # Null,
TAG # Bool(bool),
TAG # Num(String),
TAG # Str(String),
TAG # Arr(Vec<J>),
TAG # Obj(Vec<(String, J)>),
TAG # }
TAG # impl J {
TAG # fn get(&self, k: &str) -> Option<&J> {
TAG # match self {
TAG # J::Obj(v) => v.iter().find(|(a, _)| a == k).map(|(_, b)| b),
TAG # _ => None,
TAG # }
TAG # }
TAG # fn as_str(&self) -> Option<&str> {
TAG # match self {
TAG # J::Str(s) => Some(s),
TAG # _ => None,
TAG # }
TAG # }
TAG # }
TAG # struct P<'a> {
TAG # b: &'a [u8],
TAG # i: usize,
TAG # }
TAG # impl<'a> P<'a> {
TAG # fn ws(&mut self) {
TAG # while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\t' | b'\r') {
TAG # self.i += 1;
TAG # }
TAG # }
TAG # fn lit(&mut self, w: &str, v: J) -> Result<J, String> {
TAG # if self.b[self.i..].starts_with(w.as_bytes()) {
TAG # self.i += w.len();
TAG # Ok(v)
TAG # } else {
TAG # Err(format!("bad literal at {}", self.i))
TAG # }
TAG # }
TAG # fn hex4(&mut self) -> Result<u32, String> {
TAG # let h = self.b.get(self.i..self.i + 4).ok_or("short \\u")?;
TAG # let h = std::str::from_utf8(h).map_err(|e| e.to_string())?;
TAG # self.i += 4;
TAG # u32::from_str_radix(h, 16).map_err(|e| e.to_string())
TAG # }
TAG # fn string(&mut self) -> Result<String, String> {
TAG # if self.b.get(self.i) != Some(&b'"') {
TAG # return Err(format!("expected string at {}", self.i));
TAG # }
TAG # self.i += 1;
TAG # let mut out: Vec<u8> = Vec::new();
TAG # loop {
TAG # let c = *self.b.get(self.i).ok_or("unterminated string")?;
TAG # self.i += 1;
TAG # match c {
TAG # b'"' => return String::from_utf8(out).map_err(|e| e.to_string()),
TAG # b'\\' => {
TAG # let e = *self.b.get(self.i).ok_or("bad escape")?;
TAG # self.i += 1;
TAG # let ch = match e {
TAG # b'"' => '"',
TAG # b'\\' => '\\',
TAG # b'/' => '/',
TAG # b'b' => '\u{8}',
TAG # b'f' => '\u{c}',
TAG # b'n' => '\n',
TAG # b'r' => '\r',
TAG # b't' => '\t',
TAG # b'u' => {
TAG # let hi = self.hex4()?;
TAG # if (0xD800..0xDC00).contains(&hi) {
TAG # if self.b.get(self.i) != Some(&b'\\') || self.b.get(self.i + 1) != Some(&b'u') {
TAG # return Err("lone surrogate".into());
TAG # }
TAG # self.i += 2;
TAG # let lo = self.hex4()?;
TAG # char::from_u32(0x10000 + ((hi - 0xD800) << 10) + (lo.wrapping_sub(0xDC00)))
TAG # .ok_or("bad pair")?
TAG # } else {
TAG # char::from_u32(hi).ok_or("lone surrogate")?
TAG # }
TAG # }
TAG # _ => return Err("bad escape".into()),
TAG # };
TAG # let mut buf = [0u8; 4];
TAG # out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
TAG # }
TAG # _ => out.push(c),
TAG # }
TAG # }
TAG # }
TAG # fn val(&mut self) -> Result<J, String> {
TAG # self.ws();
TAG # match self.b.get(self.i).copied() {
TAG # None => Err("eof".into()),
TAG # Some(b'{') => {
TAG # self.i += 1;
TAG # let mut v = Vec::new();
TAG # self.ws();
TAG # if self.b.get(self.i) == Some(&b'}') {
TAG # self.i += 1;
TAG # return Ok(J::Obj(v));
TAG # }
TAG # loop {
TAG # self.ws();
TAG # let k = self.string()?;
TAG # self.ws();
TAG # if self.b.get(self.i) != Some(&b':') {
TAG # return Err("expected colon".into());
TAG # }
TAG # self.i += 1;
TAG # let x = self.val()?;
TAG # v.push((k, x));
TAG # self.ws();
TAG # match self.b.get(self.i) {
TAG # Some(b',') => self.i += 1,
TAG # Some(b'}') => {
TAG # self.i += 1;
TAG # return Ok(J::Obj(v));
TAG # }
TAG # _ => return Err("bad object".into()),
TAG # }
TAG # }
TAG # }
TAG # Some(b'[') => {
TAG # self.i += 1;
TAG # let mut v = Vec::new();
TAG # self.ws();
TAG # if self.b.get(self.i) == Some(&b']') {
TAG # self.i += 1;
TAG # return Ok(J::Arr(v));
TAG # }
TAG # loop {
TAG # v.push(self.val()?);
TAG # self.ws();
TAG # match self.b.get(self.i) {
TAG # Some(b',') => self.i += 1,
TAG # Some(b']') => {
TAG # self.i += 1;
TAG # return Ok(J::Arr(v));
TAG # }
TAG # _ => return Err("bad array".into()),
TAG # }
TAG # }
TAG # }
TAG # Some(b'"') => Ok(J::Str(self.string()?)),
TAG # Some(b't') => self.lit("true", J::Bool(true)),
TAG # Some(b'f') => self.lit("false", J::Bool(false)),
TAG # Some(b'n') => self.lit("null", J::Null),
TAG # Some(_) => {
TAG # let st = self.i;
TAG # while self.i < self.b.len() && matches!(self.b[self.i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') {
TAG # self.i += 1;
TAG # }
TAG # if st == self.i {
TAG # return Err(format!("unexpected byte at {st}"));
TAG # }
TAG # Ok(J::Num(String::from_utf8_lossy(&self.b[st..self.i]).into_owned()))
TAG # }
TAG # }
TAG # }
TAG # }
TAG # fn parse_json(s: &str) -> Result<J, String> {
TAG # let mut p = P { b: s.as_bytes(), i: 0 };
TAG # let v = p.val()?;
TAG # p.ws();
TAG # if p.i != p.b.len() {
TAG # return Err("trailing data".into());
TAG # }
TAG # Ok(v)
TAG # }
TAG # fn to_s(j: &J) -> String {
TAG # match j {
TAG # J::Null => "null".into(),
TAG # J::Bool(b) => b.to_string(),
TAG # J::Num(n) => n.clone(),
TAG # J::Str(s) => format!("{s:?}"),
TAG # J::Arr(v) => format!("[{}]", v.iter().map(to_s).collect::<Vec<_>>().join(",")),
TAG # J::Obj(v) => format!("{{{}}}", v.iter().map(|(k, x)| format!("{k:?}:{}", to_s(x))).collect::<Vec<_>>().join(",")),
TAG # }
TAG # }
TAG # use std::os::unix::fs::PermissionsExt;
TAG # // ---------------------------------------------------------------- isolated environment with a staging area
TAG # struct Out {
TAG # code: Option<i32>,
TAG # out: Vec<u8>,
TAG # err: Vec<u8>,
TAG # }
TAG # impl Out {
TAG # fn text(&self) -> String {
TAG # String::from_utf8_lossy(&self.out).into_owned()
TAG # }
TAG # }
TAG # fn fnv(b: &[u8]) -> u64 {
TAG # let mut h = 0xcbf29ce484222325u64;
TAG # for x in b {
TAG # h ^= *x as u64;
TAG # h = h.wrapping_mul(0x100000001b3);
TAG # }
TAG # h
TAG # }
TAG # // never follows a symlink: links are recorded by their own target text, directories and files with their mode bits
TAG # fn walk(base: &Path, dir: &Path, acc: &mut Vec<String>) {
TAG # let mut ents: Vec<_> = match std::fs::read_dir(dir) {
TAG # Ok(r) => r.filter_map(|e| e.ok()).collect(),
TAG # Err(_) => return,
TAG # };
TAG # ents.sort_by_key(|e| e.file_name());
TAG # for e in ents {
TAG # let p = e.path();
TAG # let rel = p.strip_prefix(base).unwrap().to_string_lossy().into_owned();
TAG # let md = match std::fs::symlink_metadata(&p) {
TAG # Ok(m) => m,
TAG # Err(_) => continue,
TAG # };
TAG # let mode = md.permissions().mode();
TAG # let ft = md.file_type();
TAG # if ft.is_symlink() {
TAG # acc.push(format!("l {rel} {:?}", std::fs::read_link(&p).ok()));
TAG # } else if ft.is_dir() {
TAG # acc.push(format!("d {rel} {mode:o}"));
TAG # walk(base, &p, acc);
TAG # } else if ft.is_file() {
TAG # let b = std::fs::read(&p).unwrap_or_default();
TAG # acc.push(format!("f {rel} {mode:o} {} {:x}", b.len(), fnv(&b)));
TAG # } else {
TAG # acc.push(format!("o {rel} {mode:o}"));
TAG # }
TAG # }
TAG # }
TAG # fn unlock(dir: &Path) {
TAG # if let Ok(md) = std::fs::symlink_metadata(dir) {
TAG # if md.file_type().is_dir() {
TAG # let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755));
TAG # if let Ok(r) = std::fs::read_dir(dir) {
TAG # for e in r.filter_map(|e| e.ok()) {
TAG # unlock(&e.path());
TAG # }
TAG # }
TAG # }
TAG # }
TAG # }
TAG # struct Env {
TAG # root: PathBuf,
TAG # }
TAG # impl Env {
TAG # fn new(name: &str) -> Env {
TAG # static N: AtomicUsize = AtomicUsize::new(0);
TAG # #[cfg(target_os = "macos")]
TAG # let base = PathBuf::from("/tmp"); // keep Unix socket names below SUN_LEN
TAG # #[cfg(not(target_os = "macos"))]
TAG # let base = std::env::temp_dir();
TAG # let root = base.join(format!(
TAG # "icfb-{}-{}-{name}",
TAG # std::process::id(),
TAG # N.fetch_add(1, Ordering::Relaxed)
TAG # ));
TAG # let _ = std::fs::remove_dir_all(&root);
TAG # for d in ["home", "data", "local", "cfg", "state", "cache", "cwd", "in", "stage", "outside"] {
TAG # std::fs::create_dir_all(root.join(d)).unwrap();
TAG # }
TAG # std::fs::write(root.join("outside").join("OUTSIDE_TARGET_SECRET_731"), b"top secret").unwrap();
TAG # std::fs::create_dir_all(root.join("outside").join("OUTSIDE_DIR_SECRET_731")).unwrap();
TAG # std::fs::write(root.join("outside").join("OUTSIDE_DIR_SECRET_731").join("inner_731"), b"x").unwrap();
TAG # std::fs::write(root.join("home").join("sentinel"), b"home sentinel").unwrap();
TAG # Env { root }
TAG # }
TAG # // an empty observation root inside the staging area
TAG # fn dir(&self, name: &str) -> PathBuf {
TAG # let p = self.root.join("stage").join(name);
TAG # std::fs::create_dir_all(&p).unwrap();
TAG # p
TAG # }
TAG # fn put(&self, name: &str, bytes: &[u8]) -> PathBuf {
TAG # let p = self.root.join("in").join(name);
TAG # std::fs::write(&p, bytes).unwrap();
TAG # p
TAG # }
TAG # fn snapshot(&self) -> Vec<String> {
TAG # let mut acc = Vec::new();
TAG # walk(&self.root, &self.root, &mut acc);
TAG # acc
TAG # }
TAG # fn exec_raw(&self, args: &[&str], stdin: &[u8], envs: &[(&str, &str)], snap: bool) -> Out {
TAG # let before = if snap { self.snapshot() } else { Vec::new() };
TAG # let mut c = Command::new(bin());
TAG # c.args(args)
TAG # .current_dir(self.root.join("cwd"))
TAG # .env("HOME", self.root.join("home"))
TAG # .env("XDG_DATA_HOME", self.root.join("data"))
TAG # .env("XDG_CONFIG_HOME", self.root.join("cfg"))
TAG # .env("XDG_STATE_HOME", self.root.join("state"))
TAG # .env("XDG_CACHE_HOME", self.root.join("cache"))
TAG # .env("LOCALAPPDATA", self.root.join("local"))
TAG # .env("APPDATA", self.root.join("local"));
TAG # for (k, _) in std::env::vars() {
TAG # if k.starts_with("INSTINCT_") {
TAG # c.env_remove(k);
TAG # }
TAG # }
TAG # for (k, v) in envs {
TAG # c.env(k, v);
TAG # }
TAG # c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
TAG # let mut child = c.spawn().unwrap();
TAG # let mut si = child.stdin.take().unwrap();
TAG # let data = stdin.to_vec();
TAG # let w = std::thread::spawn(move || {
TAG # let _ = si.write_all(&data);
TAG # });
TAG # let (tx, rx) = std::sync::mpsc::channel();
TAG # std::thread::spawn(move || {
TAG # let _ = tx.send(child.wait_with_output());
TAG # });
TAG # let o = rx.recv_timeout(Duration::from_secs(180)).expect("instinct check observe hung").unwrap();
TAG # let _ = w.join();
TAG # if snap {
TAG # let after = self.snapshot();
TAG # assert_eq!(before, after, "observation changed the filesystem: {args:?}");
TAG # }
TAG # Out { code: o.status.code(), out: o.stdout, err: o.stderr }
TAG # }
TAG # }
TAG # impl Drop for Env {
TAG # fn drop(&mut self) {
TAG # unlock(&self.root);
TAG # let _ = std::fs::remove_dir_all(&self.root);
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- fixtures built with std only
TAG # fn put_file(root: &Path, rel: &str) {
TAG # let p = root.join(rel);
TAG # if let Some(parent) = p.parent() {
TAG # std::fs::create_dir_all(parent).unwrap();
TAG # }
TAG # std::fs::write(p, b"contents").unwrap();
TAG # }
TAG # // ---------------------------------------------------------------- policy builder
TAG # #[derive(Clone)]
TAG # struct Pol {
TAG # schema: String,
TAG # assum: Option<String>,
TAG # allowed: String,
TAG # required: Option<String>,
TAG # scope: Option<String>,
TAG # limits: Option<String>,
TAG # extra: String,
TAG # }
TAG # fn pol(allowed: &[&str]) -> Pol {
TAG # Pol {
TAG # schema: "\"instinct.artifact-policy/v1\"".into(),
TAG # assum: Some("{\"trusted_quiescent_staging\":true}".into()),
TAG # allowed: jl(allowed),
TAG # required: None,
TAG # scope: None,
TAG # limits: None,
TAG # extra: String::new(),
TAG # }
TAG # }
TAG # // a JSON array of strings; items are already JSON-escaped text
TAG # fn jl(items: &[&str]) -> String {
TAG # format!("[{}]", items.iter().map(|s| format!("\"{s}\"")).collect::<Vec<_>>().join(","))
TAG # }
TAG # impl Pol {
TAG # fn required(mut self, items: &[&str]) -> Pol {
TAG # self.required = Some(jl(items));
TAG # self
TAG # }
TAG # fn scope(mut self, s: &str) -> Pol {
TAG # self.scope = Some(s.into());
TAG # self
TAG # }
TAG # fn schema(mut self, s: &str) -> Pol {
TAG # self.schema = s.into();
TAG # self
TAG # }
TAG # fn extra(mut self, s: &str) -> Pol {
TAG # self.extra.push_str(s);
TAG # self
TAG # }
TAG # fn json(&self) -> String {
TAG # let mut t = format!("{{\"schema\":{}", self.schema);
TAG # if let Some(a) = &self.assum {
TAG # t.push_str(&format!(",\"assumptions\":{a}"));
TAG # }
TAG # t.push_str(&format!(",\"allowed\":{}", self.allowed));
TAG # if let Some(r) = &self.required {
TAG # t.push_str(&format!(",\"required\":{r}"));
TAG # }
TAG # if let Some(s) = &self.scope {
TAG # t.push_str(&format!(",\"scope\":{s}"));
TAG # }
TAG # if let Some(l) = &self.limits {
TAG # t.push_str(&format!(",\"limits\":{l}"));
TAG # }
TAG # t.push_str(&self.extra);
TAG # t.push('}');
TAG # t
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- small helpers
TAG # fn trunc(s: &str) -> String {
TAG # s.chars().take(500).collect()
TAG # }
TAG # fn obj(o: &Out) -> J {
TAG # let t = o.text();
TAG # parse_json(t.trim()).unwrap_or_else(|e| panic!("stdout is not one JSON value ({e}): {}", trunc(&t)))
TAG # }
TAG # fn sf<'a>(j: &'a J, k: &str) -> &'a str {
TAG # j.get(k).and_then(J::as_str).unwrap_or_else(|| panic!("missing string field {k} in {}", trunc(&to_s(j))))
TAG # }
TAG # fn is_root() -> bool {
TAG # let probe = std::env::temp_dir().join(format!("instinct-fb-probe-{}", std::process::id()));
TAG # let _ = std::fs::remove_dir_all(&probe);
TAG # std::fs::create_dir_all(&probe).unwrap();
TAG # std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o000)).unwrap();
TAG # let readable = std::fs::read_dir(&probe).is_ok();
TAG # let _ = std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o755));
TAG # let _ = std::fs::remove_dir_all(&probe);
TAG # readable
TAG # }
TAG # fn has_hex64(s: &str) -> bool {
TAG # let b = s.as_bytes();
TAG # let mut run = 0;
TAG # for &c in b {
TAG # if matches!(c, b'0'..=b'9' | b'a'..=b'f') {
TAG # run += 1;
TAG # if run >= 64 {
TAG # return true;
TAG # }
TAG # } else {
TAG # run = 0;
TAG # }
TAG # }
TAG # false
TAG # }
TAG # const LEGACY_EVAL_KEYS: [&str; 16] = [
TAG # "schema", "since", "generated", "lessons", "proven", "delivery_record", "paid_off", "misled", "to_quarantine", "delivered_never_judged",
TAG # "never_fired", "near_duplicates", "savings", "next_actions", "applied_quarantine", "explore",
TAG # ];
TAG # fn key_list(j: &J) -> Vec<String> {
TAG # match j {
TAG # J::Obj(v) => v.iter().map(|(k, _)| k.clone()).collect(),
TAG # _ => panic!("object"),
TAG # }
TAG # }
TAG # // the same tree without lock files, which the contract allows to appear
TAG # fn tree(env: &Env) -> Vec<String> {
TAG # env.snapshot().into_iter().filter(|l| !l.to_lowercase().contains("lock")).collect()
TAG # }
TAG # // ---------------------------------------------------------------- the fixture: a bank, a lesson, a staging root
TAG # #[derive(Debug, Clone)]
TAG # struct Sum {
TAG # present: bool,
TAG # total: u64,
TAG # claimed: u64,
TAG # verified: u64,
TAG # downgraded: u64,
TAG # invalid: u64,
TAG # }
TAG # struct Fx {
TAG # env: Env,
TAG # store: PathBuf,
TAG # root: PathBuf,
TAG # id: String,
TAG # n: usize,
TAG # }
TAG # impl Fx {
TAG # fn new(name: &str, native: bool) -> Fx {
TAG # let env = Env::new(name);
TAG # std::fs::create_dir_all(env.root.join("banks")).unwrap();
TAG # let store = env.root.join("banks").join(if native { "bank.hxdb" } else { "bank.jsonl" });
TAG # let root = env.dir("staging");
TAG # put_file(&root, "release.bin");
TAG # let mut fx = Fx { env, store, root, id: String::new(), n: 0 };
TAG # fx.id = fx.bank_lesson(&["--project", "release-lab"]);
TAG # fx
TAG # }
TAG # fn st(&self) -> &str {
TAG # self.store.to_str().unwrap()
TAG # }
TAG # fn envs(&self) -> Vec<(&'static str, &'static str)> {
TAG # vec![("INSTINCT_PROJECT", "release-lab")]
TAG # }
TAG # fn cli(&self, args: &[&str]) -> Out {
TAG # self.env.exec_raw(args, b"", &self.envs(), false)
TAG # }
TAG # fn cli_env(&self, args: &[&str], envs: &[(&str, &str)]) -> Out {
TAG # self.env.exec_raw(args, b"", envs, false)
TAG # }
TAG # fn bank_lesson(&self, scope: &[&str]) -> String {
TAG # let mut a = vec!["bank", "--store", self.st(), "--title", "Ship only release", "--when", "Packaging the release", "--found", "Stray files get shipped", "--how", "Check the inventory", "--evidence", "seen twice"];
TAG # a.extend_from_slice(scope);
TAG # let o = self.cli_env(&a, &[]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # let t = o.text();
TAG # t.split_whitespace().nth(1).unwrap_or_else(|| panic!("{t}")).to_string()
TAG # }
TAG # fn policy(&self, allowed: &[&str], required: &[&str]) -> String {
TAG # pol(allowed).required(required).scope("{\"project\":\"release-lab\"}").json()
TAG # }
TAG # fn std_policy(&self) -> String {
TAG # self.policy(&["release.bin"], &["release.bin"])
TAG # }
TAG # fn attach_for(&mut self, id: &str, policy: &str) -> Out {
TAG # self.n += 1;
TAG # self.env.exec_raw(&["check", "attach", "--lesson", id, "--store", self.st(), "--input", "-"], policy.as_bytes(), &self.envs(), false)
TAG # }
TAG # fn attach(&mut self, policy: &str) -> Out {
TAG # let id = self.id.clone();
TAG # self.attach_for(&id, policy)
TAG # }
TAG # fn attached(&mut self) {
TAG # let p = self.std_policy();
TAG # let o = self.attach(&p);
TAG # assert_eq!(o.code, Some(0), "attach: {}", trunc(&o.text()));
TAG # }
TAG # fn hit_check_with(&self, id: &str, key: &str, note: &str, trusted: bool, root: &Path, envs: &[(&str, &str)]) -> Out {
TAG # let mut a = vec!["hit", id, "--check", "--root", root.to_str().unwrap(), "--outcome-id", key, "--store", self.st(), "--note", note];
TAG # if trusted {
TAG # a.push("--trusted-staging");
TAG # }
TAG # self.cli_env(&a, envs)
TAG # }
TAG # fn hit_check(&self, key: &str, note: &str) -> Out {
TAG # self.hit_check_with(&self.id, key, note, true, &self.root, &self.envs())
TAG # }
TAG # fn events(&self) -> Vec<J> {
TAG # let o = self.cli(&["export", "--store", self.st()]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # o.text().lines().filter(|l| !l.trim().is_empty()).map(|l| parse_json(l).unwrap_or_else(|e| panic!("export line {e}: {l}"))).collect()
TAG # }
TAG # fn hits_of(&self, id: &str) -> Vec<J> {
TAG # self.events().into_iter().filter(|e| e.get("kind").and_then(J::as_str) == Some("hit") && e.get("id").and_then(J::as_str) == Some(id)).collect()
TAG # }
TAG # fn hits(&self) -> Vec<J> {
TAG # let id = self.id.clone();
TAG # self.hits_of(&id)
TAG # }
TAG # fn misses(&self) -> usize {
TAG # self.events().iter().filter(|e| e.get("kind").and_then(J::as_str) == Some("miss")).count()
TAG # }
TAG # fn verified_events(&self) -> usize {
TAG # self.events().iter().filter(|e| e.get("check_verification").is_some()).count()
TAG # }
TAG # fn eval_json(&self, since: &str) -> J {
TAG # let o = self.cli(&["eval", "--json", "--since", since, "--store", self.st()]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # obj(&o)
TAG # }
TAG # fn eval_text(&self) -> String {
TAG # let o = self.cli(&["eval", "--since", "all", "--store", self.st()]);
TAG # assert_eq!(o.code, Some(0));
TAG # o.text()
TAG # }
TAG # // the documented summary (docs/check-verified-feedback.md): absent entirely when the bank has no verification marker
TAG # fn summary(&self, since: &str) -> Sum {
TAG # let j = self.eval_json(since);
TAG # // Legacy savings.hits is all-time. Verification and paid_off are windowed.
TAG # let total = match j.get("paid_off") {
TAG # Some(J::Arr(rows)) => rows.iter().map(|r| match r.get("hits") { Some(J::Num(n)) => n.parse::<u64>().unwrap(), other => panic!("paid_off hits: {other:?}") }).sum(),
TAG # other => panic!("paid_off: {other:?}"),
TAG # };
TAG # let num = |v: &J, k: &str| -> u64 {
TAG # match v.get(k) {
TAG # Some(J::Num(n)) => n.parse::<u64>().unwrap_or_else(|_| panic!("{k}: {n}")),
TAG # other => panic!("verification.{k} must be a number, got {other:?}"),
TAG # }
TAG # };
TAG # let s = match j.get("verification") {
TAG # None => {
TAG # assert_eq!(key_list(&j), LEGACY_EVAL_KEYS.to_vec(), "no marker, no new keys");
TAG # Sum { present: false, total, claimed: total, verified: 0, downgraded: 0, invalid: 0 }
TAG # }
TAG # Some(v) => {
TAG # assert_eq!(sf(v, "schema"), "instinct.verified-feedback-summary/v1");
TAG # let s = Sum { present: true, total, claimed: num(v, "claimed_hits"), verified: num(v, "check_verified_hits"), downgraded: num(v, "downgraded_hits"), invalid: num(v, "invalid_records") };
TAG # for k in LEGACY_EVAL_KEYS {
TAG # assert!(key_list(&j).contains(&k.to_string()), "legacy key {k} stays");
TAG # }
TAG # s
TAG # }
TAG # };
TAG # assert_eq!(s.claimed + s.verified, s.total, "claimed_hits = total hits - check_verified_hits: {}", trunc(&to_s(&j)));
TAG # assert!(s.verified <= s.total && s.downgraded <= s.claimed, "verified is a subset of hits and downgraded a subset of claimed: {}", trunc(&to_s(&j)));
TAG # s
TAG # }
TAG # fn verified_count(&self, since: &str) -> u64 {
TAG # self.summary(since).verified
TAG # }
TAG # fn append_event(&self, line: &str) {
TAG # let mut t = std::fs::read_to_string(&self.store).unwrap();
TAG # if !t.ends_with('\n') {
TAG # t.push('\n');
TAG # }
TAG # t.push_str(line);
TAG # t.push('\n');
TAG # std::fs::write(&self.store, t).unwrap();
TAG # }
TAG # fn bank_titled(&self, title: &str, scope: &[&str]) -> String {
TAG # let mut a = vec!["bank", "--store", self.st(), "--title", title, "--when", "Another packaging situation", "--found", "Other stray files", "--how", "Look at the folder list", "--evidence", "seen once"];
TAG # a.extend_from_slice(scope);
TAG # let o = self.cli_env(&a, &[]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # o.text().split_whitespace().nth(1).unwrap().to_string()
TAG # }
TAG # fn rewrite_store(&self, f: impl Fn(&str) -> String) {
TAG # let t = std::fs::read_to_string(&self.store).unwrap();
TAG # std::fs::write(&self.store, f(&t)).unwrap();
TAG # }
TAG # }
TAG # // a hit that was not recorded: no hit event and no claim of success on stdout
TAG # fn not_recorded(fx: &Fx, o: &Out, ctx: &str) {
TAG # assert!(fx.hits().is_empty(), "{ctx}: a hit was recorded: {}", trunc(&o.text()));
TAG # assert!(!(o.code == Some(0) && o.text().contains("hit recorded")), "{ctx}: claims a hit: {}", trunc(&o.text()));
TAG # }
TAG # // exactly one verified hit with the documented evidence, and no private content
TAG # fn one_verified(fx: &Fx, key: &str, o: &Out) -> J {
TAG # assert_eq!(o.code, Some(0), "expected a recorded verified hit: {} / {}", trunc(&o.text()), trunc(&String::from_utf8_lossy(&o.err)));
TAG # let hits = fx.hits();
TAG # assert_eq!(hits.len(), 1, "exactly one hit: {}", trunc(&to_s(&J::Arr(hits.clone()))));
TAG # let ev = &hits[0];
TAG # for k in ["kind", "id", "ts", "note", "outcome_id"] {
TAG # assert!(ev.get(k).is_some(), "the legacy hit fields stay: {k}");
TAG # }
TAG # assert_eq!(sf(ev, "outcome_id"), key);
TAG # let cv = ev.get("check_verification").unwrap_or_else(|| panic!("a verified hit carries check_verification: {}", trunc(&to_s(ev))));
TAG # let t = to_s(cv);
TAG # for needle in ["adapter_observed", "not_evaluated", "artifact-inventory/v1", key, fx.id.as_str()] {
TAG # assert!(t.contains(needle), "check_verification must carry {needle}: {t}");
TAG # }
TAG # assert!(has_hex64(&t), "check_verification must carry a SHA-256: {t}");
TAG # let line = to_s(ev);
TAG # assert!(!line.contains(fx.root.to_str().unwrap()), "the root path must never be stored: {line}");
TAG # assert!(!o.text().contains(fx.root.to_str().unwrap()), "the root path must not be displayed");
TAG # ev.clone()
TAG # }
TAG # // ================================================================ 1. forged "it worked" with a hidden extra file
TAG # #[test]
TAG # fn a_forged_it_worked_with_a_hidden_extra_file_earns_no_hit_and_fixing_the_fixture_earns_exactly_one() {
TAG # for native in [false, true] {
TAG # let mut fx = Fx::new(if native { "forged-native" } else { "forged-jsonl" }, native);
TAG # fx.attached();
TAG # put_file(&fx.root, ".hidden-extra");
TAG # let before = tree(&fx.env);
TAG # let o = fx.hit_check("run-1", "it worked");
TAG # not_recorded(&fx, &o, "hidden extra");
TAG # assert_eq!(before, tree(&fx.env), "a failed check must leave the bank and sidecar unchanged");
TAG # assert_eq!(fx.verified_count("all"), 0);
TAG # assert_eq!(fx.verified_events(), 0);
TAG # // the failed attempt did not consume the outcome key; fix only the fixture
TAG # std::fs::remove_file(fx.root.join(".hidden-extra")).unwrap();
TAG # let o = fx.hit_check("run-1", "it worked");
TAG # one_verified(&fx, "run-1", &o);
TAG # assert_eq!(fx.verified_count("all"), 1);
TAG # // retry: no extra hit, nothing changes
TAG # let before = tree(&fx.env);
TAG # let o = fx.hit_check("run-1", "it worked");
TAG # assert_eq!(fx.hits().len(), 1, "a retry earns nothing");
TAG # assert!(!(o.code == Some(0) && o.text().contains("hit recorded for")) || o.text().contains("already"), "{}", trunc(&o.text()));
TAG # assert_eq!(before, tree(&fx.env), "a retry changes nothing");
TAG # assert_eq!(fx.verified_events(), 1, "one receipt event");
TAG # }
TAG # }
TAG # #[test]
TAG # fn a_missing_required_file_also_earns_no_hit() {
TAG # let mut fx = Fx::new("required-missing", false);
TAG # fx.attached();
TAG # std::fs::remove_file(fx.root.join("release.bin")).unwrap();
TAG # let o = fx.hit_check("k", "it worked");
TAG # not_recorded(&fx, &o, "required file missing");
TAG # put_file(&fx.root, "release.bin");
TAG # let o = fx.hit_check("k", "it worked");
TAG # one_verified(&fx, "k", &o);
TAG # }
TAG # // ================================================================ 2. claimed hits stay claimed
TAG # #[test]
TAG # fn a_claimed_hit_cannot_be_promoted_by_a_verified_retry() {
TAG # let mut fx = Fx::new("claimed", false);
TAG # fx.attached();
TAG # let o = fx.cli(&["hit", &fx.id.clone(), "--note", "claimed", "--outcome-id", "k", "--store", &fx.st().to_string()]);
TAG # assert_eq!(o.code, Some(0));
TAG # assert_eq!(fx.hits().len(), 1);
TAG # assert!(fx.hits()[0].get("check_verification").is_none());
TAG # let before = tree(&fx.env);
TAG # let o = fx.hit_check("k", "now verified");
TAG # assert_eq!(fx.hits().len(), 1, "no second credit: {}", trunc(&o.text()));
TAG # assert!(fx.hits()[0].get("check_verification").is_none(), "a claimed hit stays claimed");
TAG # assert_eq!(fx.verified_events(), 0);
TAG # assert_eq!(fx.verified_count("all"), 0);
TAG # assert_eq!(before, tree(&fx.env), "nothing is mutated by the retry");
TAG # // a different outcome is a different observation and may earn its own verified hit
TAG # let o = fx.hit_check("k2", "verified");
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # assert_eq!(fx.hits().len(), 2);
TAG # assert_eq!(fx.verified_events(), 1);
TAG # assert_eq!(fx.verified_count("all"), 1);
TAG # }
TAG # // ================================================================ 3. the gates: nothing earns a hit without every precondition
TAG # #[test]
TAG # fn every_missing_precondition_earns_no_hit() {
TAG # let mut fx = Fx::new("gates", false);
TAG # let id = fx.id.clone();
TAG # // no attachment: --check never falls back to claimed feedback
TAG # let o = fx.hit_check("k", "it worked");
TAG # not_recorded(&fx, &o, "no attachment");
TAG # assert_ne!(o.code, Some(0), "no attachment is an error: {}", trunc(&o.text()));
TAG # fx.attached();
TAG # let before = tree(&fx.env);
TAG # // the caller's explicit acknowledgement is required on every verified hit
TAG # let o = fx.hit_check_with(&id, "k", "it worked", false, &fx.root, &fx.envs());
TAG # not_recorded(&fx, &o, "no --trusted-staging");
TAG # assert_ne!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # // the root is required and absolute
TAG # let st = fx.st().to_string();
TAG # for args in [
TAG # vec!["hit", &id, "--check", "--trusted-staging", "--outcome-id", "k", "--store", &st],
TAG # vec!["hit", &id, "--check", "--trusted-staging", "--root", "staging", "--outcome-id", "k", "--store", &st],
TAG # vec!["hit", &id, "--check", "--trusted-staging", "--root", "", "--outcome-id", "k", "--store", &st],
TAG # vec!["hit", &id, "--check", "--trusted-staging", "--root", "~/x", "--outcome-id", "k", "--store", &st],
TAG # ] {
TAG # let o = fx.cli(&args);
TAG # not_recorded(&fx, &o, &format!("{args:?}"));
TAG # assert_ne!(o.code, Some(0), "{args:?}");
TAG # }
TAG # // empty and whitespace observation keys are rejected
TAG # for key in ["", " ", " ", "\t", "\n"] {
TAG # let o = fx.hit_check(key, "it worked");
TAG # not_recorded(&fx, &o, &format!("key {key:?}"));
TAG # assert_ne!(o.code, Some(0), "key {key:?}");
TAG # }
TAG # for flag in ["--trusted-staging=false", "--trusted-staging=0", "--check=false"] {
TAG # let mut args = vec!["hit", id.as_str(), "--check", "--root", fx.root.to_str().unwrap(), "--outcome-id", "false-grant", "--store", st.as_str()];
TAG # args.push(flag);
TAG # let out = fx.cli(&args);
TAG # assert_ne!(out.code, Some(0), "false or repeated grant flag must be refused: {flag}");
TAG # assert!(fx.hits().is_empty());
TAG # }
TAG # // the miss path has no check mode
TAG # let o = fx.cli(&["miss", &id, "--check", "--root", fx.root.to_str().unwrap(), "--trusted-staging", "--outcome-id", "m", "--store", &st]);
TAG # assert_ne!(o.code, Some(0), "miss --check is an error: {}", trunc(&o.text()));
TAG # assert_eq!(fx.misses(), 0, "no miss was recorded either");
TAG # assert!(fx.hits().is_empty());
TAG # // an absent lesson
TAG # let o = fx.hit_check_with("in-doesnotexist", "k", "n", true, &fx.root, &fx.envs());
TAG # assert_ne!(o.code, Some(0));
TAG # assert!(fx.hits_of("in-doesnotexist").is_empty());
TAG # assert_eq!(before, tree(&fx.env), "none of these changed anything");
TAG # // and the control: with everything in place the hit is earned
TAG # let o = fx.hit_check("k", "fine");
TAG # one_verified(&fx, "k", &o);
TAG # }
TAG # #[test]
TAG # fn the_current_scope_cannot_be_overridden_by_the_attachment_or_the_request() {
TAG # let mut fx = Fx::new("scope-gate", false);
TAG # fx.attached();
TAG # let id = fx.id.clone();
TAG # // a different current project: the lesson is out of scope, whatever the attachment says
TAG # let o = fx.hit_check_with(&id, "k", "it worked", true, &fx.root, &[("INSTINCT_PROJECT", "other-project")]);
TAG # not_recorded(&fx, &o, "wrong current project");
TAG # // Extra unrestricted dimensions are tested after the zero-credit negative cases below.
TAG # let o = fx.hit_check_with(&id, "k", "it worked", true, &fx.root, &[("INSTINCT_PROJECT", "release-lab-2")]);
TAG # not_recorded(&fx, &o, "near-miss project name");
TAG # let o = fx.hit_check_with(&id, "k", "it worked", true, &fx.root, &[("INSTINCT_PROJECT", "Release-Lab")]);
TAG # not_recorded(&fx, &o, "case-different project");
TAG # // an attachment must equal the lesson's scope exactly: neither narrower, broader nor different
TAG # let wide = pol(&["release.bin"]).required(&["release.bin"]).scope("{}").json();
TAG # let o = fx.attach(&wide);
TAG # assert_ne!(o.code, Some(0), "an attachment must not broaden a project-scoped lesson: {}", trunc(&o.text()));
TAG # let narrow = pol(&["release.bin"]).required(&["release.bin"]).scope("{\"project\":\"release-lab\",\"machine\":\"m1\"}").json();
TAG # assert_ne!(fx.attach(&narrow).code, Some(0), "or narrow it");
TAG # let other = pol(&["release.bin"]).required(&["release.bin"]).scope("{\"project\":\"other\"}").json();
TAG # assert_ne!(fx.attach(&other).code, Some(0), "or change it");
TAG # let extra = fx.hit_check_with(&id, "unrestricted-persona", "ok", true, &fx.root, &[("INSTINCT_PROJECT", "release-lab"), ("INSTINCT_PERSONA", "someone")]);
TAG # assert_eq!(extra.code, Some(0), "extra unrestricted scope must not block a valid hit");
TAG # // a lesson with two scope dimensions needs both
TAG # let id2 = fx.bank_lesson(&["--project", "release-lab", "--persona", "p1"]);
TAG # let one_dim = pol(&["release.bin"]).scope("{\"project\":\"release-lab\"}").json();
TAG # assert_ne!(fx.attach_for(&id2, &one_dim).code, Some(0));
TAG # let two_dim = pol(&["release.bin"]).scope("{\"project\":\"release-lab\",\"persona\":\"p1\"}").json();
TAG # assert_eq!(fx.attach_for(&id2, &two_dim).code, Some(0));
TAG # let o = fx.hit_check_with(&id2, "k", "n", true, &fx.root, &[("INSTINCT_PROJECT", "release-lab"), ("INSTINCT_PERSONA", "p2")]);
TAG # assert!(fx.hits_of(&id2).is_empty(), "wrong persona: {}", trunc(&o.text()));
TAG # let o = fx.hit_check_with(&id2, "k", "n", true, &fx.root, &[("INSTINCT_PROJECT", "release-lab"), ("INSTINCT_PERSONA", "p1")]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # assert_eq!(fx.hits_of(&id2).len(), 1);
TAG # }
TAG # #[test]
TAG # fn expired_quarantined_and_absent_lessons_earn_nothing_and_attachments_need_a_real_lesson() {
TAG # // expired: a lesson whose validity ended
TAG # let mut fx = Fx::new("expired", false);
TAG # fx.attached();
TAG # fx.rewrite_store(|t| t.replace("\"valid_until\":0", "\"valid_until\":1000"));
TAG # let o = fx.hit_check("k", "it worked");
TAG # not_recorded(&fx, &o, "expired lesson");
TAG # // quarantined
TAG # let mut fx = Fx::new("quarantined", true);
TAG # fx.attached();
TAG # let id = fx.id.clone();
TAG # let o = fx.cli(&["review", &id, "--state", "quarantined", "--reason", "misleading", "--source-ref", "test", "--store", &fx.st().to_string()]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # let o = fx.hit_check("k", "it worked");
TAG # not_recorded(&fx, &o, "quarantined lesson");
TAG # // an attachment to an absent lesson is an error and stores nothing
TAG # let before = tree(&fx.env);
TAG # let p = fx.std_policy();
TAG # let o = fx.attach_for("in-doesnotexist", &p);
TAG # assert_ne!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # assert_eq!(before, tree(&fx.env));
TAG # let o = fx.hit_check_with("in-doesnotexist", "k", "n", true, &fx.root, &fx.envs());
TAG # assert_ne!(o.code, Some(0));
TAG # }
TAG # // ================================================================ 4. observations that must not record
TAG # fn assert_nothing_recorded(fx: &Fx, root: &Path, ctx: &str) {
TAG # let before = tree(&fx.env);
TAG # let o = fx.hit_check_with(&fx.id, "k-branch", "it worked", true, root, &fx.envs());
TAG # not_recorded(fx, &o, ctx);
TAG # assert_eq!(fx.verified_events(), 0, "{ctx}");
TAG # assert_eq!(before, tree(&fx.env), "{ctx}: bank and sidecar must be unchanged");
TAG # }
TAG # #[test]
TAG # fn failed_abstained_missing_unreadable_symlinked_and_oversized_observations_record_nothing() {
TAG # let mut fx = Fx::new("branches", false);
TAG # fx.attached();
TAG # let env = &fx.env;
TAG # // missing root and a file as root
TAG # assert_nothing_recorded(&fx, &env.root.join("stage").join("does-not-exist"), "missing root");
TAG # let file = env.put("not-a-dir", b"x");
TAG # assert_nothing_recorded(&fx, &file, "root is a file");
TAG # // an empty root abstains from nothing: the required file is simply absent
TAG # let empty = env.dir("empty-root");
TAG # assert_nothing_recorded(&fx, &empty, "empty root fails the required check");
TAG # // symlink bypass variants
TAG # let real = env.dir("REAL_TARGET_731");
TAG # put_file(&real, "release.bin");
TAG # let alias = env.root.join("stage").join("alias");
TAG # std::os::unix::fs::symlink(&real, &alias).unwrap();
TAG # assert_nothing_recorded(&fx, &alias, "root is a symlink to a clean tree");
TAG # for spelling in ["alias/", "alias//", "alias/.", "alias/./"] {
TAG # assert_nothing_recorded(&fx, &PathBuf::from(format!("{}/{spelling}", env.root.join("stage").display())), spelling);
TAG # }
TAG # let parent_alias = env.root.join("stage").join("palias");
TAG # std::os::unix::fs::symlink(env.root.join("stage"), &parent_alias).unwrap();
TAG # assert_nothing_recorded(&fx, &parent_alias.join("REAL_TARGET_731"), "symlink in an ancestor of the root");
TAG # let inner = env.dir("inner-link");
TAG # put_file(&inner, "release.bin");
TAG # std::os::unix::fs::symlink(real.join("release.bin"), inner.join("link")).unwrap();
TAG # assert_nothing_recorded(&fx, &inner, "symlink entry inside the tree");
TAG # let sock_root = env.dir("sock-root");
TAG # put_file(&sock_root, "release.bin");
TAG # #[cfg(target_os = "linux")]
TAG # let socket_dir = std::fs::File::open(&sock_root).unwrap();
TAG # #[cfg(target_os = "linux")]
TAG # let socket_path = { use std::os::fd::AsRawFd; PathBuf::from(format!("/proc/self/fd/{}/sock", socket_dir.as_raw_fd())) };
TAG # #[cfg(not(target_os = "linux"))]
TAG # let socket_path = sock_root.join("sock");
TAG # let _l = std::os::unix::net::UnixListener::bind(socket_path).unwrap();
TAG # assert_nothing_recorded(&fx, &sock_root, "unsupported entry kind");
TAG # drop(_l);
TAG # // unreadable nested directory
TAG # if !is_root() {
TAG # let locked = env.dir("locked-root");
TAG # put_file(&locked, "release.bin");
TAG # put_file(&locked, "sub/inner");
TAG # std::fs::set_permissions(locked.join("sub"), std::fs::Permissions::from_mode(0o000)).unwrap();
TAG # assert_nothing_recorded(&fx, &locked, "unreadable nested directory");
TAG # std::fs::set_permissions(locked.join("sub"), std::fs::Permissions::from_mode(0o755)).unwrap();
TAG # }
TAG # // an observation whose exact result cannot fit the output budget
TAG # let big = env.dir("big-root");
TAG # put_file(&big, "release.bin");
TAG # let names: Vec<String> = (0..400).map(|i| format!("{i:03}{}", "n".repeat(252))).collect();
TAG # for n in &names {
TAG # put_file(&big, n);
TAG # }
TAG # let mut allowed: Vec<&str> = vec!["release.bin"];
TAG # allowed.extend(names.iter().map(|s| s.as_str()));
TAG # let big_policy = pol(&allowed).required(&["release.bin"]).scope("{\"project\":\"release-lab\"}").json();
TAG # let mut fx2 = Fx::new("branches-big", false);
TAG # let o = fx2.attach(&big_policy);
TAG # if o.code == Some(0) {
TAG # assert_nothing_recorded(&fx2, &big, "output-limit observation");
TAG # }
TAG # // the control: the clean tree still earns exactly one verified hit afterwards
TAG # let o = fx.hit_check("k-branch", "ok");
TAG # one_verified(&fx, "k-branch", &o);
TAG # }
TAG # // ================================================================ 5. bindings
TAG # #[test]
TAG # fn changing_the_policy_or_the_lesson_invalidates_the_binding() {
TAG # // changed policy: the outcome key cannot be reused for a second credit
TAG # let mut fx = Fx::new("rebind-policy", false);
TAG # fx.attached();
TAG # let o = fx.hit_check("k", "first");
TAG # one_verified(&fx, "k", &o);
TAG # let p2 = fx.policy(&["release.bin", "extra-allowed"], &["release.bin"]);
TAG # let o = fx.attach(&p2);
TAG # assert_eq!(o.code, Some(0), "replacing a policy is an explicit new revision: {}", trunc(&o.text()));
TAG # let before = tree(&fx.env);
TAG # let o = fx.hit_check("k", "second");
TAG # assert_eq!(fx.hits().len(), 1, "no second credit: {}", trunc(&o.text()));
TAG # assert_eq!(before, tree(&fx.env));
TAG # assert_eq!(fx.verified_count("all"), 1);
TAG # // changed lesson content under a reused id (a trusted local edit of the bank file)
TAG # let mut fx = Fx::new("rebind-lesson", false);
TAG # fx.attached();
TAG # fx.rewrite_store(|t| t.replace("\"how\":\"Check the inventory\"", "\"how\":\"Ship everything in the folder\""));
TAG # let before = tree(&fx.env);
TAG # let o = fx.hit_check("k", "it worked");
TAG # not_recorded(&fx, &o, "lesson content changed after attachment");
TAG # assert_eq!(before, tree(&fx.env));
TAG # // a fresh attachment re-binds the new content
TAG # fx.attached();
TAG # let o = fx.hit_check("k", "it worked");
TAG # one_verified(&fx, "k", &o);
TAG # }
TAG # #[test]
TAG # fn attaching_is_idempotent_and_alters_neither_recall_nor_the_bank() {
TAG # let mut fx = Fx::new("attach", false);
TAG # let id = fx.id.clone();
TAG # let st0 = fx.st().to_string();
TAG # let recall_args = ["recall", "--q", "Packaging the release", "--k", "1", "--store", st0.as_str()];
TAG # let recall_before = fx.cli(&recall_args).out;
TAG # let bank_before = std::fs::read(&fx.store).unwrap();
TAG # let p = fx.std_policy();
TAG # let o = fx.attach(&p);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # assert_eq!(std::fs::read(&fx.store).unwrap(), bank_before, "attaching does not write the bank");
TAG # assert_eq!(fx.cli(&recall_args).out, recall_before, "attaching does not change recall");
TAG # assert!(fx.hits().is_empty(), "attaching earns no hit and runs no observation");
TAG # assert!(!o.text().contains(fx.root.to_str().unwrap()));
TAG # // identical attachment again: success, no change
TAG # let snap = tree(&fx.env);
TAG # let o = fx.attach(&p);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # assert_eq!(snap, tree(&fx.env), "a duplicate identical attachment is idempotent");
TAG # // invalid policies are errors and store nothing
TAG # let bad_policies: Vec<String> = vec![
TAG # "{".into(),
TAG # "{}".into(),
TAG # pol(&["a"]).required(&["b"]).scope("{\"project\":\"release-lab\"}").json(),
TAG # pol(&["../a"]).scope("{\"project\":\"release-lab\"}").json(),
TAG # pol(&["a"]).scope("{\"project\":\"release-lab\"}").extra(",\"root\":\"/tmp\"").json(),
TAG # pol(&["a"]).scope("{\"project\":\"release-lab\"}").schema("\"instinct.artifact-policy/v2\"").json(),
TAG # ];
TAG # for b in &bad_policies {
TAG # let o = fx.attach(b);
TAG # assert_ne!(o.code, Some(0), "{}", trunc(b));
TAG # assert_eq!(snap, tree(&fx.env), "{}", trunc(b));
TAG # }
TAG # // an explicit store is required for attach; the environment's store is not a substitute
TAG # let f = fx.env.put("p.json", p.as_bytes());
TAG # let snap = tree(&fx.env); // snapshot after harness creates the input file
TAG # let o = fx.cli_env(&["check", "attach", "--lesson", &id, "--input", f.to_str().unwrap()], &[("INSTINCT_STORE", fx.st())]);
TAG # assert_ne!(o.code, Some(0), "attach without --store");
TAG # assert_eq!(snap, tree(&fx.env));
TAG # // argument mistakes
TAG # let st = fx.st().to_string();
TAG # let fs = f.to_str().unwrap().to_string();
TAG # for args in [
TAG # vec!["check", "attach"],
TAG # vec!["check", "attach", "--lesson", &id, "--store", &st],
TAG # vec!["check", "attach", "--store", &st, "--input", &fs],
TAG # vec!["check", "attach", "--lesson", &id, "--lesson", &id, "--store", &st, "--input", &fs],
TAG # vec!["check", "attach", "--lesson", &id, "--store", &st, "--input", &fs, "extra"],
TAG # vec!["check", "attach", "--lesson", &id, "--store", &st, "--input", &fs, "--root", "/tmp"],
TAG # vec!["check", "attach", "--lesson", &id, "--store", &st, "--input", &fs, "--bogus"],
TAG # ] {
TAG # let o = fx.cli(&args);
TAG # assert_ne!(o.code, Some(0), "{args:?}");
TAG # assert_eq!(snap, tree(&fx.env), "{args:?}");
TAG # }
TAG # }
TAG # // ================================================================ 6. the no-check path is unchanged
TAG # #[test]
TAG # fn feedback_without_check_is_byte_identical_with_or_without_attachments() {
TAG # for attach in [false, true] {
TAG # let mut fx = Fx::new(if attach { "legacy-attached" } else { "legacy-plain" }, false);
TAG # if attach {
TAG # fx.attached();
TAG # }
TAG # let id = fx.id.clone();
TAG # let st = fx.st().to_string();
TAG # let o = fx.cli(&["hit", &id, "--note", "x", "--outcome-id", "k1", "--store", &st]);
TAG # assert_eq!(o.code, Some(0));
TAG # assert_eq!(o.text(), format!("hit recorded for {id}\n"));
TAG # let o = fx.cli(&["hit", &id, "--note", "x", "--outcome-id", "k1", "--store", &st]);
TAG # assert_eq!(o.text(), format!("outcome already recorded for {id}\n"));
TAG # let o = fx.cli(&["miss", &id, "--note", "y", "--store", &st]);
TAG # assert_eq!(o.text(), format!("miss recorded for {id}\n"));
TAG # let o = fx.cli(&["hit", &id, "--note", "z", &"--store".to_string(), &st]);
TAG # assert_eq!(o.text(), format!("hit recorded for {id}\n"));
TAG # let events = fx.events();
TAG # let hit = events.iter().find(|e| e.get("outcome_id").is_some()).unwrap();
TAG # assert_eq!(key_list(hit), vec!["kind", "id", "ts", "note", "outcome_id"], "the legacy hit event shape");
TAG # let plain = events.iter().filter(|e| e.get("kind").and_then(J::as_str) == Some("hit")).last().unwrap();
TAG # assert_eq!(key_list(plain), vec!["kind", "id", "ts", "note"]);
TAG # assert!(events.iter().all(|e| e.get("check_verification").is_none()));
TAG # // evaluation with no verified events: exactly the legacy keys and no verified wording
TAG # let j = fx.eval_json("all");
TAG # assert_eq!(key_list(&j), LEGACY_EVAL_KEYS.to_vec(), "no verified events, no new keys");
TAG # assert!(!fx.eval_text().to_lowercase().contains("verified"), "{}", fx.eval_text());
TAG # }
TAG # // two banks built the same way evaluate identically apart from the clock
TAG # let a = Fx::new("legacy-a", false);
TAG # let b = Fx::new("legacy-b", false);
TAG # let mut texts = Vec::new();
TAG # for fx in [&a, &b] {
TAG # let id = fx.id.clone();
TAG # fx.cli(&["hit", &id, "--note", "x", "--store", fx.st()]);
TAG # let t = fx.eval_text();
TAG # texts.push(t.replace(&id, "ID"));
TAG # }
TAG # assert_eq!(texts[0], texts[1]);
TAG # }
TAG # // ================================================================ 7. evaluation splits claimed and verified without double counting
TAG # #[test]
TAG # fn eval_separates_verified_from_claimed_counts_and_counts_each_hit_once() {
TAG # let mut fx = Fx::new("eval-split", false);
TAG # fx.attached();
TAG # let a = fx.id.clone();
TAG # let b = fx.bank_lesson(&["--project", "release-lab", "--persona", "claimed-only"]);
TAG # let st = fx.st().to_string();
TAG # let o = fx.cli(&["hit", &b, "--note", "claimed", "--outcome-id", "kb", "--store", &st]);
TAG # assert_eq!(o.code, Some(0));
TAG # let before = fx.eval_json("all");
TAG # assert_eq!(key_list(&before), LEGACY_EVAL_KEYS.to_vec(), "only claimed hits so far");
TAG # let o = fx.hit_check("ka", "verified");
TAG # one_verified(&fx, "ka", &o);
TAG # let j = fx.eval_json("all");
TAG # let keys = key_list(&j);
TAG # for k in LEGACY_EVAL_KEYS {
TAG # assert!(keys.contains(&k.to_string()), "legacy key {k} stays");
TAG # }
TAG # assert!(keys.contains(&"verification".to_string()), "a separate verified summary is appended: {keys:?}");
TAG # let s = fx.summary("all");
TAG # assert!(s.present);
TAG # assert_eq!((s.total, s.claimed, s.verified, s.downgraded, s.invalid), (2, 1, 1, 0, 0), "one verified, one claimed, each counted once: {}", trunc(&to_s(&j)));
TAG # // the totals still count each hit once: both lessons paid off exactly once
TAG # let paid = match j.get("paid_off") {
TAG # Some(J::Arr(v)) => v.clone(),
TAG # other => panic!("{other:?}"),
TAG # };
TAG # let hits_of = |id: &str| paid.iter().find(|e| sf(e, "id") == id).map(|e| to_s(e.get("hits").unwrap()));
TAG # assert_eq!(hits_of(&a).as_deref(), Some("1"), "the verified hit is one hit");
TAG # assert_eq!(hits_of(&b).as_deref(), Some("1"));
TAG # assert!(fx.eval_text().to_lowercase().contains("verified"), "{}", fx.eval_text());
TAG # // a retraction removes the credit
TAG # let o = fx.cli(&["retract", "hit", &a, "--store", &st]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # let s = fx.summary("all");
TAG # assert_eq!((s.total, s.verified, s.downgraded), (1, 0, 0), "a retracted verified hit loses its credit and is not a downgrade: {s:?}");
TAG # let j = fx.eval_json("all");
TAG # let paid = match j.get("paid_off") {
TAG # Some(J::Arr(v)) => v.clone(),
TAG # other => panic!("{other:?}"),
TAG # };
TAG # assert!(paid.iter().all(|e| sf(e, "id") != a), "the retracted hit no longer pays off");
TAG # }
TAG # #[test]
TAG # fn eval_respects_the_time_window_for_verified_hits() {
TAG # let mut fx = Fx::new("eval-window", false);
TAG # fx.attached();
TAG # let o = fx.hit_check("k", "verified");
TAG # one_verified(&fx, "k", &o);
TAG # assert_eq!(fx.verified_count("all"), 1);
TAG # assert_eq!(fx.verified_count("7d"), 1);
TAG # // move the whole hit event 90 days into the past
TAG # let ts = to_s(fx.hits()[0].get("ts").unwrap());
TAG # let old: u64 = ts.parse::<u64>().unwrap() - 90 * 86_400;
TAG # fx.rewrite_store(|t| t.replace(&format!("\"ts\":{ts},\"note\""), &format!("\"ts\":{old},\"note\"")));
TAG # assert_eq!(fx.verified_count("all"), 1, "still counted in the all-time window");
TAG # assert_eq!(fx.verified_count("7d"), 0, "outside the 7 day window");
TAG # assert_eq!(fx.verified_count("30d"), 0);
TAG # }
TAG # #[test]
TAG # fn malformed_forged_or_misbound_verification_metadata_is_never_credited() {
TAG # let mut fx = Fx::new("eval-forged", false);
TAG # fx.attached();
TAG # let a = fx.id.clone();
TAG # let o = fx.hit_check("ka", "verified");
TAG # let ev = one_verified(&fx, "ka", &o);
TAG # let cv_text = to_s(ev.get("check_verification").unwrap());
TAG # assert_eq!(fx.verified_count("all"), 1);
TAG # let original = std::fs::read_to_string(&fx.store).unwrap();
TAG # // a claimed hit on another lesson, then graft metadata onto it
TAG # let b = fx.bank_lesson(&["--project", "release-lab", "--persona", "claimed-only"]);
TAG # let st = fx.st().to_string();
TAG # fx.cli(&["hit", &b, "--note", "claimed", "--outcome-id", "kb", "--store", &st]);
TAG # let with_claimed = std::fs::read_to_string(&fx.store).unwrap();
TAG # assert_eq!(fx.verified_count("all"), 1);
TAG # let claimed_line = with_claimed.lines().find(|l| l.contains("\"outcome_id\":\"kb\"")).unwrap().to_string();
TAG # let graft = |extra: &str| {
TAG # let forged = claimed_line.replacen('}', &format!(",\"check_verification\":{extra}}}"), 1);
TAG # std::fs::write(&fx.store, with_claimed.replace(&claimed_line, &forged)).unwrap();
TAG # fx.summary("all")
TAG # };
TAG # let s = graft(&cv_text);
TAG # assert_eq!((s.total, s.verified), (2, 1), "another lesson's verification grafted onto a claimed hit is not credited: {s:?}");
TAG # for (what, extra) in [
TAG # ("an empty object", "{}"),
TAG # ("a plausible-looking stub", "{\"version\":1,\"authorization\":\"not_evaluated\",\"evidence_origin\":\"adapter_observed\"}"),
TAG # ("a bare string", "\"verified\""),
TAG # ] {
TAG # let s = graft(extra);
TAG # assert_eq!((s.total, s.verified), (2, 1), "{what} is not a receipt: {s:?}");
TAG # assert!(s.invalid >= 1, "{what} is structurally invalid metadata and is reported, not promoted: {s:?}");
TAG # }
TAG # for extra in ["true", "null"] {
TAG # let s = graft(extra);
TAG # assert_eq!((s.total, s.verified), (2, 1), "{extra}: {s:?}");
TAG # }
TAG # // the real receipt with a broken authority claim is not credited either, and is reported
TAG # if original.contains("\"authorization\":\"not_evaluated\"") {
TAG # std::fs::write(&fx.store, original.replace("\"authorization\":\"not_evaluated\"", "\"authorization\":\"granted\"")).unwrap();
TAG # let s = fx.summary("all");
TAG # assert_eq!((s.total, s.verified, s.claimed), (1, 0, 1), "a receipt that grants authority is invalid: {s:?}");
TAG # assert!(s.invalid + s.downgraded >= 1, "{s:?}");
TAG # }
TAG # if original.contains("\"evidence_origin\":\"adapter_observed\"") {
TAG # std::fs::write(&fx.store, original.replace("\"evidence_origin\":\"adapter_observed\"", "\"evidence_origin\":\"caller_reported\"")).unwrap();
TAG # let s = fx.summary("all");
TAG # assert_eq!((s.total, s.verified), (1, 0), "a receipt that is not adapter-observed is not a verified hit: {s:?}");
TAG # }
TAG # // whatever happened to the metadata, the hit itself still counts once as a claimed hit
TAG # let j = fx.eval_json("all");
TAG # let paid = match j.get("paid_off") {
TAG # Some(J::Arr(v)) => v.clone(),
TAG # other => panic!("{other:?}"),
TAG # };
TAG # assert!(paid.iter().any(|e| sf(e, "id") == a), "the event is still a hit");
TAG # }
TAG # // ================================================================ 8. concurrency
TAG # #[test]
TAG # fn concurrent_verified_requests_with_one_key_earn_one_hit_and_one_receipt() {
TAG # for native in [false, true] {
TAG # let mut fx = Fx::new(if native { "conc-native" } else { "conc-jsonl" }, native);
TAG # fx.attached();
TAG # let args: Vec<String> = ["hit", &fx.id, "--check", "--root", fx.root.to_str().unwrap(), "--trusted-staging", "--outcome-id", "same-key", "--store", fx.st(), "--note", "race"]
TAG # .iter()
TAG # .map(|s| s.to_string())
TAG # .collect();
TAG # let mut kids = Vec::new();
TAG # for _ in 0..6 {
TAG # let mut c = Command::new(bin());
TAG # c.args(&args)
TAG # .current_dir(fx.env.root.join("cwd"))
TAG # .env("HOME", fx.env.root.join("home"))
TAG # .env("XDG_DATA_HOME", fx.env.root.join("data"))
TAG # .env("INSTINCT_PROJECT", "release-lab")
TAG # .stdin(Stdio::null())
TAG # .stdout(Stdio::piped())
TAG # .stderr(Stdio::piped());
TAG # for (k, _) in std::env::vars() {
TAG # if k.starts_with("INSTINCT_") && k != "INSTINCT_PROJECT" {
TAG # c.env_remove(k);
TAG # }
TAG # }
TAG # kids.push(c.spawn().unwrap());
TAG # }
TAG # let mut ok = 0;
TAG # for k in kids {
TAG # let o = k.wait_with_output().unwrap();
TAG # assert!(o.status.code().is_some(), "killed by a signal");
TAG # assert!(!String::from_utf8_lossy(&o.stderr).contains("panicked"), "{}", String::from_utf8_lossy(&o.stderr));
TAG # if o.status.code() == Some(0) {
TAG # ok += 1;
TAG # }
TAG # }
TAG # assert!(ok >= 1, "at least one request succeeds");
TAG # assert_eq!(fx.hits().len(), 1, "one key, one hit (native={native})");
TAG # assert_eq!(fx.verified_events(), 1, "one receipt event");
TAG # assert_eq!(fx.verified_count("all"), 1);
TAG # let _ = fx.events();
TAG # }
TAG # // distinct keys are distinct outcomes: none is lost
TAG # let mut fx = Fx::new("conc-distinct", true);
TAG # fx.attached();
TAG # let mut kids = Vec::new();
TAG # for i in 0..3 {
TAG # let key = format!("key-{i}");
TAG # let mut c = Command::new(bin());
TAG # c.args(["hit", &fx.id, "--check", "--root", fx.root.to_str().unwrap(), "--trusted-staging", "--outcome-id", &key, "--store", fx.st()])
TAG # .current_dir(fx.env.root.join("cwd"))
TAG # .env("HOME", fx.env.root.join("home"))
TAG # .env("XDG_DATA_HOME", fx.env.root.join("data"))
TAG # .env("INSTINCT_PROJECT", "release-lab")
TAG # .stdin(Stdio::null())
TAG # .stdout(Stdio::piped())
TAG # .stderr(Stdio::piped());
TAG # kids.push(c.spawn().unwrap());
TAG # }
TAG # for k in kids {
TAG # let o = k.wait_with_output().unwrap();
TAG # assert_eq!(o.status.code(), Some(0), "{}", String::from_utf8_lossy(&o.stdout));
TAG # }
TAG # assert_eq!(fx.hits().len(), 3);
TAG # assert_eq!(fx.verified_events(), 3);
TAG # }
TAG # // ================================================================ 9. formats, migration and old readers
TAG # #[test]
TAG # fn verified_hits_survive_migration_and_do_not_break_plain_commands() {
TAG # let mut fx = Fx::new("migrate", false);
TAG # fx.attached();
TAG # let o = fx.hit_check("k", "verified");
TAG # let ev = one_verified(&fx, "k", &o);
TAG # let cv = to_s(ev.get("check_verification").unwrap());
TAG # let new_store = fx.env.root.join("banks").join("migrated.hxdb");
TAG # let o = fx.cli(&["migrate", "--store", fx.st(), "--to", new_store.to_str().unwrap()]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # let migrated = Fx { env: Env { root: fx.env.root.clone() }, store: new_store.clone(), root: fx.root.clone(), id: fx.id.clone(), n: 0 };
TAG # let hits = migrated.hits();
TAG # assert_eq!(hits.len(), 1, "counts preserved");
TAG # assert_eq!(to_s(hits[0].get("check_verification").unwrap()), cv, "the evidence binding is preserved");
TAG # assert_eq!(migrated.verified_count("all"), 1);
TAG # std::mem::forget(migrated);
TAG # // plain commands keep working on a bank that holds verified events (an old reader would count a hit, never verify it)
TAG # let id = fx.id.clone();
TAG # let st = fx.st().to_string();
TAG # let recall = fx.cli(&["recall", "--q", "Packaging the release", "--k", "1", "--store", &st]);
TAG # assert_eq!(recall.code, Some(0));
TAG # assert!(recall.text().contains("1 hit"), "{}", trunc(&recall.text()));
TAG # for args in [
TAG # vec!["stats", "--store", &st],
TAG # vec!["eval", "--store", &st],
TAG # vec!["instincts", "--store", &st],
TAG # vec!["export", "--store", &st],
TAG # ] {
TAG # let o = fx.cli(&args);
TAG # assert_eq!(o.code, Some(0), "{args:?}: {}", trunc(&o.text()));
TAG # }
TAG # let o = fx.cli(&["miss", &id, "--note", "later miss", "--store", &st]);
TAG # assert_eq!(o.code, Some(0));
TAG # let o = fx.cli(&["retract", "miss", &id, "--store", &st]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # assert_eq!(fx.verified_count("all"), 1, "the verified hit is untouched by unrelated feedback");
TAG # }
TAG # // ================================================================ 10. privacy
TAG # #[test]
TAG # fn nothing_private_leaks_into_events_outputs_or_the_sidecar() {
TAG # let mut fx = Fx::new("privacy", false);
TAG # let secret = "PRIVATE-SENTINEL_731.txt";
TAG # put_file(&fx.root, secret);
TAG # let p = fx.policy(&["release.bin", secret], &["release.bin"]);
TAG # let o = fx.attach(&p);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # let o = fx.hit_check("k", "verified");
TAG # let ev = one_verified(&fx, "k", &o);
TAG # let root_s = fx.root.to_str().unwrap().to_string();
TAG # let line = to_s(&ev);
TAG # assert!(!line.contains(secret), "file names from the observation are not exported in the event: {line}");
TAG # assert!(!o.text().contains(secret), "{}", o.text());
TAG # for text in [fx.eval_text(), to_s(&fx.eval_json("all")), fx.cli(&["recall", "--q", "Packaging the release", "--store", fx.st()]).text()] {
TAG # assert!(!text.contains(secret) && !text.contains(&root_s), "{}", trunc(&text));
TAG # }
TAG # // no stored file anywhere (bank, sidecar, journals) holds the root path: it is never an executable grant
TAG # let mut found = Vec::new();
TAG # for e in std::fs::read_dir(fx.env.root.join("banks")).unwrap().filter_map(|e| e.ok()) {
TAG # if let Ok(b) = std::fs::read(e.path()) {
TAG # if String::from_utf8_lossy(&b).contains(&root_s) {
TAG # found.push(e.path());
TAG # }
TAG # }
TAG # }
TAG # assert!(found.is_empty(), "the root path was stored in {found:?}");
TAG # // the sidecar exists beside the bank and is private
TAG # let side: Vec<_> = std::fs::read_dir(fx.env.root.join("banks")).unwrap().filter_map(|e| e.ok()).filter(|e| e.file_name().to_string_lossy().contains("capabilities")).collect();
TAG # assert!(!side.is_empty(), "the attachment sidecar `<bank>.capabilities.hxdb` must exist beside the bank");
TAG # for e in side {
TAG # let mode = std::fs::metadata(e.path()).unwrap().permissions().mode() & 0o777;
TAG # assert_eq!(mode & 0o077, 0, "{:?} must be private, mode {mode:o}", e.path());
TAG # }
TAG # }
TAG # // ================================================================ 11. MCP
TAG # fn mcp(fx: &Fx, envs: &[(&str, &str)], requests: &[String]) -> Vec<String> {
TAG # let mut all: Vec<(&str, &str)> = vec![("INSTINCT_STORE", fx.st()), ("INSTINCT_PROJECT", "release-lab")];
TAG # all.extend_from_slice(envs);
TAG # let input = requests.join("\n") + "\n";
TAG # let o = fx.env.exec_raw(&["mcp"], input.as_bytes(), &all, false);
TAG # o.text().lines().map(|l| l.to_string()).collect()
TAG # }
TAG # fn feedback(id: &str, extra: &str) -> String {
TAG # format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"instinct_feedback\",\"arguments\":{{\"id\":\"{id}\",\"paid_off\":true,\"note\":\"it worked\"{extra}}}}}}}")
TAG # }
TAG # fn is_error(line: &str) -> bool {
TAG # line.contains("\"isError\":true") || line.contains("\"error\"")
TAG # }
TAG # #[test]
TAG # fn mcp_verified_feedback_needs_an_explicit_server_grant_and_never_trusts_the_request() {
TAG # let mut fx = Fx::new("mcp", false);
TAG # fx.attached();
TAG # let id = fx.id.clone();
TAG # let root = fx.root.to_str().unwrap().to_string();
TAG # let chk = |key: &str, more: &str| feedback(&id, &format!(",\"check\":true,\"outcome_id\":\"{key}\"{more}"));
TAG # // default denied: no server grant, whatever the request says
TAG # let before = tree(&fx.env);
TAG # let r = mcp(&fx, &[], &[chk("m1", ",\"trusted_staging\":true"), chk("m2", &format!(",\"trusted_staging\":true,\"root\":\"{root}\"")), chk("m3", &format!(",\"trusted_staging\":true,\"check_root\":\"{root}\""))]);
TAG # assert_eq!(r.len(), 3, "{r:?}");
TAG # assert!(r.iter().all(|l| is_error(l)), "no INSTINCT_CHECK_ROOT, no observation: {r:?}");
TAG # assert!(fx.hits().is_empty());
TAG # assert_eq!(before, tree(&fx.env));
TAG # // a grant without the request's own acknowledgement
TAG # let grant = [("INSTINCT_CHECK_ROOT", root.as_str())];
TAG # let r = mcp(&fx, &grant, &[chk("m4", ""), chk("m5", ",\"trusted_staging\":false"), chk("m6", ",\"trusted_staging\":\"true\""), chk("m7", ",\"trusted_staging\":1")]);
TAG # assert!(r.iter().all(|l| is_error(l)), "{r:?}");
TAG # assert!(fx.hits().is_empty());
TAG # // a miss cannot be checked, and checked feedback cannot rest on the note alone
TAG # let r = mcp(&fx, &grant, &[format!("{{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{{\"name\":\"instinct_feedback\",\"arguments\":{{\"id\":\"{id}\",\"paid_off\":false,\"note\":\"n\",\"check\":true,\"outcome_id\":\"m8\",\"trusted_staging\":true}}}}}}")]);
TAG # assert!(is_error(&r[0]), "{r:?}");
TAG # assert!(fx.hits().is_empty() && fx.misses() == 0);
TAG # let r = mcp(&fx, &grant, &[chk("", ",\"trusted_staging\":true"), chk(" ", ",\"trusted_staging\":true")]);
TAG # assert!(r.iter().all(|l| is_error(l)), "{r:?}");
TAG # assert!(fx.hits().is_empty());
TAG # // the grant names one root; a different root in the request does not move it
TAG # let dirty = fx.env.dir("dirty-root");
TAG # put_file(&dirty, "release.bin");
TAG # put_file(&dirty, ".hidden-extra");
TAG # let dirty_s = dirty.to_str().unwrap().to_string();
TAG # let r = mcp(&fx, &[("INSTINCT_CHECK_ROOT", dirty_s.as_str())], &[chk("m9", &format!(",\"trusted_staging\":true,\"root\":\"{root}\"")), chk("m10", ",\"trusted_staging\":true")]);
TAG # assert!(fx.hits().is_empty(), "the clean root in the request must not replace the dirty grant: {r:?}");
TAG # // the note 'it worked' never substitutes for the check
TAG # assert!(r.iter().all(|l| !l.contains("hit recorded")), "{r:?}");
TAG # // with the matching grant and acknowledgement the hit is earned once
TAG # let r = mcp(&fx, &grant, &[chk("m11", ",\"trusted_staging\":true"), chk("m11", ",\"trusted_staging\":true")]);
TAG # assert_eq!(r.len(), 2, "{r:?}");
TAG # assert!(!is_error(&r[0]), "{r:?}");
TAG # assert!(r.iter().all(|l| !l.contains(&root)), "the granted root path is not echoed: {r:?}");
TAG # let hits = fx.hits();
TAG # assert_eq!(hits.len(), 1, "a retry with the same key earns nothing");
TAG # assert!(hits[0].get("check_verification").is_some());
TAG # assert_eq!(fx.verified_count("all"), 1);
TAG # }
TAG # #[test]
TAG # fn cli_and_mcp_verified_hits_have_the_same_evidence_shape_and_plain_feedback_is_unchanged() {
TAG # let mut fx = Fx::new("parity", false);
TAG # fx.attached();
TAG # let a = fx.id.clone();
TAG # let b = fx.bank_lesson(&["--project", "release-lab", "--persona", "second"]);
TAG # let p2 = pol(&["release.bin"]).required(&["release.bin"]).scope("{\"project\":\"release-lab\",\"persona\":\"second\"}").json();
TAG # assert_eq!(fx.attach_for(&b, &p2).code, Some(0));
TAG # let o = fx.hit_check("kc", "cli");
TAG # let cli_ev = one_verified(&fx, "kc", &o);
TAG # let root = fx.root.to_str().unwrap().to_string();
TAG # let grant = [("INSTINCT_CHECK_ROOT", root.as_str()), ("INSTINCT_PERSONA", "second")];
TAG # let r = mcp(&fx, &grant, &[feedback(&b, ",\"check\":true,\"outcome_id\":\"km\",\"trusted_staging\":true")]);
TAG # assert!(!is_error(&r[0]), "{r:?}");
TAG # let mcp_hits = fx.hits_of(&b);
TAG # assert_eq!(mcp_hits.len(), 1);
TAG # let keys = |e: &J| match e.get("check_verification") {
TAG # Some(J::Obj(v)) => v.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(),
TAG # other => panic!("{other:?}"),
TAG # };
TAG # assert_eq!(keys(&cli_ev), keys(&mcp_hits[0]), "the CLI and MCP record the same evidence fields");
TAG # assert_eq!(key_list(&cli_ev), key_list(&mcp_hits[0]), "and the same event shape");
TAG # // plain MCP feedback (no check) is unchanged and records a claimed hit
TAG # let r = mcp(&fx, &[], &[feedback(&a, ",\"outcome_id\":\"plain\"")]);
TAG # assert!(!is_error(&r[0]), "{r:?}");
TAG # let plain: Vec<J> = fx.hits_of(&a).into_iter().filter(|e| e.get("outcome_id").and_then(J::as_str) == Some("plain")).collect();
TAG # assert_eq!(plain.len(), 1);
TAG # assert!(plain[0].get("check_verification").is_none());
TAG # assert_eq!(key_list(&plain[0]), vec!["kind", "id", "ts", "note", "outcome_id"]);
TAG # // `check` absent or false is the ordinary path
TAG # let r = mcp(&fx, &[], &[feedback(&a, ",\"check\":false,\"outcome_id\":\"plain2\"")]);
TAG # assert!(!is_error(&r[0]), "{r:?}");
TAG # assert!(fx.hits_of(&a).iter().filter(|e| e.get("outcome_id").and_then(J::as_str) == Some("plain2")).all(|e| e.get("check_verification").is_none()));
TAG # }
TAG # // ================================================================ 12. the consolidation fold (JSONL: supersede events are appended as public events)
TAG # fn supersede(fx: &Fx, member: &str, by: &str) {
TAG # fx.append_event(&format!("{{\"kind\":\"supersede\",\"id\":\"{member}\",\"by\":\"{by}\"}}"));
TAG # }
TAG # fn two_lessons(name: &str) -> (Fx, String, String) {
TAG # let mut fx = Fx::new(name, false);
TAG # let a = fx.id.clone();
TAG # let b = fx.bank_titled("Second lesson about shipping", &["--project", "release-lab"]);
TAG # let p = fx.std_policy();
TAG # assert_eq!(fx.attach_for(&a, &p).code, Some(0));
TAG # assert_eq!(fx.attach_for(&b, &p).code, Some(0));
TAG # (fx, a, b)
TAG # }
TAG # fn earn(fx: &Fx, id: &str, key: &str) {
TAG # let o = fx.hit_check_with(id, key, "verified", true, &fx.root, &fx.envs());
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # }
TAG # #[test]
TAG # fn a_verified_credit_moved_by_supersede_to_another_lesson_is_downgraded_to_claimed() {
TAG # let (fx, a, b) = two_lessons("fold-transfer");
TAG # earn(&fx, &b, "kb");
TAG # let s = fx.summary("all");
TAG # assert!(s.present);
TAG # assert_eq!((s.total, s.claimed, s.verified, s.downgraded, s.invalid), (1, 0, 1, 0, 0), "{s:?}");
TAG # // B is folded into A: the credit survives consolidation, but a verification claim never moves between lessons
TAG # supersede(&fx, &b, &a);
TAG # let s = fx.summary("all");
TAG # assert_eq!(s.total, 1, "the credit survives consolidation once: {s:?}");
TAG # assert_eq!(s.verified, 0, "scopes matching is not a reason to transfer verification: {s:?}");
TAG # assert_eq!(s.claimed, 1, "{s:?}");
TAG # assert_eq!(s.downgraded, 1, "the downgrade is reported separately: {s:?}");
TAG # assert_eq!(s.invalid, 0, "a downgrade is not an invalid record: {s:?}");
TAG # assert!(fx.eval_text().to_lowercase().contains("verified"), "the text section matches the JSON summary");
TAG # // the verified hit on the surviving lesson itself is still verified
TAG # earn(&fx, &a, "ka");
TAG # let s = fx.summary("all");
TAG # assert_eq!((s.total, s.verified, s.downgraded), (2, 1, 1), "{s:?}");
TAG # // undoing the consolidation restores the original binding
TAG # let o = fx.cli(&["unsupersede", &b, "--store", fx.st()]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # let s = fx.summary("all");
TAG # assert_eq!((s.total, s.verified, s.downgraded), (2, 2, 0), "{s:?}");
TAG # }
TAG # #[test]
TAG # fn mixed_claimed_and_verified_reports_of_one_consolidated_outcome_count_once_and_are_claimed() {
TAG # let (fx, a, b) = two_lessons("fold-mixed");
TAG # let st = fx.st().to_string();
TAG # // the same outcome key reported as a plain claim on A and as a verified check on B
TAG # let o = fx.cli(&["hit", &a, "--note", "claimed", "--outcome-id", "same", "--store", &st]);
TAG # assert_eq!(o.code, Some(0));
TAG # earn(&fx, &b, "same");
TAG # let s = fx.summary("all");
TAG # assert_eq!((s.total, s.verified), (2, 1), "before consolidation they are two lessons' outcomes: {s:?}");
TAG # supersede(&fx, &b, &a);
TAG # let s = fx.summary("all");
TAG # assert_eq!(s.total, 1, "one consolidated outcome is one credit: {s:?}");
TAG # assert_eq!(s.verified, 0, "a mixed report is claimed unless every live contributing mark stays bound: {s:?}");
TAG # assert_eq!(s.claimed, 1, "{s:?}");
TAG # // a second verified report of the same key on the survivor does not add a credit
TAG # let o = fx.hit_check_with(&a, "same", "again", true, &fx.root, &fx.envs());
TAG # let s = fx.summary("all");
TAG # assert_eq!(s.total, 1, "no second credit: {} {s:?}", trunc(&o.text()));
TAG # }
TAG # #[test]
TAG # fn a_changed_lesson_downgrades_its_verified_credit_and_reports_it() {
TAG # let mut fx = Fx::new("fold-content", false);
TAG # fx.attached();
TAG # let o = fx.hit_check("k", "verified");
TAG # one_verified(&fx, "k", &o);
TAG # let s = fx.summary("all");
TAG # assert_eq!((s.total, s.verified, s.downgraded), (1, 1, 0), "{s:?}");
TAG # fx.rewrite_store(|t| t.replace("\"how\":\"Check the inventory\"", "\"how\":\"Ship everything in the folder\""));
TAG # let s = fx.summary("all");
TAG # assert_eq!(s.total, 1, "the hit itself still counts: {s:?}");
TAG # assert_eq!(s.verified, 0, "the receipt no longer binds the current lesson content: {s:?}");
TAG # assert_eq!(s.claimed, 1, "{s:?}");
TAG # assert_eq!(s.downgraded, 1, "{s:?}");
TAG # assert_eq!(s.invalid, 0, "{s:?}");
TAG # // the original receipt event is not rewritten by evaluation
TAG # assert!(fx.hits()[0].get("check_verification").is_some());
TAG # }
TAG # #[test]
TAG # fn retraction_removes_the_credit_without_a_second_vote_and_disputes_follow_the_existing_fold() {
TAG # let mut fx = Fx::new("fold-retract", false);
TAG # fx.attached();
TAG # let id = fx.id.clone();
TAG # let st = fx.st().to_string();
TAG # earn(&fx, &id, "k");
TAG # let o = fx.cli(&["retract", "hit", &id, "--store", &st]);
TAG # assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
TAG # let s = fx.summary("all");
TAG # assert_eq!((s.total, s.verified, s.claimed, s.downgraded), (0, 0, 0, 0), "a retracted verified hit disappears entirely: {s:?}");
TAG # assert_eq!(s.invalid, 0, "{s:?}");
TAG # // a conflicting verdict on a verified outcome never creates a second credit
TAG # let (fx2, a2, _b2) = two_lessons("fold-dispute");
TAG # earn(&fx2, &a2, "kd");
TAG # let st2 = fx2.st().to_string();
TAG # let o = fx2.cli(&["miss", &a2, "--note", "disputed", "--outcome-id", "kd", "--store", &st2]);
TAG # let _ = o;
TAG # let s = fx2.summary("all");
TAG # assert!(s.total <= 1, "one outcome, at most one credit: {s:?}");
TAG # assert!(s.verified <= s.total);
TAG # // a plain claim with the same key afterwards does not upgrade, duplicate or change a verified credit
TAG # let (fx3, a3, _b3) = two_lessons("fold-retry");
TAG # earn(&fx3, &a3, "kr");
TAG # let st3 = fx3.st().to_string();
TAG # let o = fx3.cli(&["hit", &a3, "--note", "claimed", "--outcome-id", "kr", "--store", &st3]);
TAG # assert_eq!(o.text(), format!("outcome already recorded for {a3}\n"));
TAG # let o = fx3.hit_check_with(&a3, "kr", "again", true, &fx3.root, &fx3.envs());
TAG # let _ = o;
TAG # let s = fx3.summary("all");
TAG # assert_eq!((s.total, s.verified, s.claimed), (1, 1, 0), "retries change nothing: {s:?}");
TAG # assert_eq!(fx3.hits_of(&a3).len(), 1);
TAG # assert_eq!(fx3.verified_events(), 1);
TAG # }
TAG # #[test]
TAG # fn the_window_uses_the_event_times_selected_by_consolidation() {
TAG # let mut fx = Fx::new("fold-window", false);
TAG # fx.attached();
TAG # let id = fx.id.clone();
TAG # earn(&fx, &id, "old");
TAG # earn(&fx, &id, "new");
TAG # let line = |key: &str| fx.events().into_iter().find(|e| e.get("outcome_id").and_then(J::as_str) == Some(key)).map(|e| to_s(e.get("ts").unwrap())).unwrap();
TAG # let ts_old = line("old").parse::<u64>().unwrap();
TAG # let moved = ts_old - 90 * 86_400;
TAG # fx.rewrite_store(|t| {
TAG # t.lines()
TAG # .map(|l| if l.contains("\"outcome_id\":\"old\"") { l.replacen(&format!("\"ts\":{ts_old},"), &format!("\"ts\":{moved},"), 1) } else { l.to_string() })
TAG # .collect::<Vec<_>>()
TAG # .join("\n")
TAG # + "\n"
TAG # });
TAG # let all = fx.summary("all");
TAG # assert_eq!((all.total, all.verified), (2, 2), "{all:?}");
TAG # for w in ["7d", "30d"] {
TAG # let s = fx.summary(w);
TAG # assert_eq!((s.total, s.verified, s.claimed), (1, 1, 0), "{w}: only the recent verified hit is in the window: {s:?}");
TAG # }
TAG # // a claimed-only bank has no verification section at all, in any window
TAG # let plain = Fx::new("fold-plain", false);
TAG # let pid = plain.id.clone();
TAG # plain.cli(&["hit", &pid, "--note", "c", "--store", plain.st()]);
TAG # for w in ["7d", "30d", "all"] {
TAG # let s = plain.summary(w);
TAG # assert!(!s.present, "{w}");
TAG # assert_eq!(s.total, 1);
TAG # }
TAG # }
TAG # }