use super::{parse_json, Discovery, Json};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
pub(super) const DIR: &str = ".instinct";
pub(super) const FILE: &str = "lessons.jsonl";
const ATTRIBUTES: &str = "lessons.jsonl merge=union\n";
const IGNORED: [&str; 3] = ["*.lock", "*.idx", "*.idx.tmp*"];
static HOOK_CWD: Mutex<Option<String>> = Mutex::new(None);
pub(super) static WRITING_TEAM: AtomicBool = AtomicBool::new(false);
static NOTED: AtomicBool = AtomicBool::new(false);
static SEQ: AtomicU64 = AtomicU64::new(0);
pub(super) fn set_cwd(cwd: Option<&str>) {
if let (Some(c), Ok(mut slot)) = (cwd.filter(|c| Path::new(c).is_absolute()), HOOK_CWD.lock()) {
*slot = Some(c.to_string());
}
}
pub(super) fn enabled() -> bool {
std::env::var("INSTINCT_TEAM").map_or(true, |v| v.trim() != "0")
}
fn home() -> Option<PathBuf> {
std::env::var_os("HOME")
.filter(|v| !v.is_empty())
.or_else(|| std::env::var_os("USERPROFILE").filter(|v| !v.is_empty()))
.map(PathBuf::from)
}
pub(super) fn find_from(start: &Path, home: Option<&Path>) -> Option<PathBuf> {
for dir in start.ancestors() {
if home.is_some_and(|h| h == dir) {
return None;
}
let candidate = dir.join(DIR).join(FILE);
if candidate.is_file() {
return Some(candidate);
}
if dir.join(".git").exists() {
return None;
}
}
None
}
pub(super) fn find(user_store: &Path) -> Option<PathBuf> {
if !enabled() {
return None;
}
let hooked = HOOK_CWD.lock().ok().and_then(|g| g.clone()).map(PathBuf::from);
let start = hooked.or_else(|| std::env::current_dir().ok())?;
let found = find_from(&start, home().as_deref())?;
let same = |a: &Path, b: &Path| match (a.canonicalize(), b.canonicalize()) {
(Ok(a), Ok(b)) => a == b,
_ => a == b,
};
if same(&found, user_store) {
return None;
}
Some(found)
}
fn note(path: &Path, skipped: usize, first: usize) {
if skipped > 0 && !NOTED.swap(true, Ordering::Relaxed) {
eprintln!(
"instinct: skipped {skipped} unreadable line(s) in {} (first at line {first}); the rest is used",
path.display()
);
}
}
pub(super) fn normalize(text: &str, path: &Path) -> String {
let mut seen: HashSet<&str> = HashSet::new();
let mut rows: Vec<(u8, u64, &str)> = Vec::new();
let (mut skipped, mut first) = (0usize, 0usize);
for (n, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || !seen.insert(line) {
continue;
}
let usable = match parse_json(line) {
Ok(v @ Json::Obj(_)) => {
let kind = v.get("kind").and_then(Json::as_str).unwrap_or("");
let machine_missing = kind == "machine_discovery"
&& v.get("scope_machine").and_then(Json::as_str).unwrap_or("").trim().is_empty();
(!machine_missing).then(|| {
let rank = u8::from(!matches!(kind, "discovery" | "machine_discovery"));
(rank, v.get("ts").and_then(Json::as_f64).unwrap_or(0.0) as u64)
})
}
_ => None,
};
match usable {
Some((rank, ts)) => rows.push((rank, ts, line)),
None => {
if skipped == 0 {
first = n + 1;
}
skipped += 1;
}
}
}
note(path, skipped, first);
rows.sort();
let mut out = String::with_capacity(text.len() + 1);
for (_, _, line) in rows {
out.push_str(line);
out.push('\n');
}
out
}
pub(super) fn load(path: &Path) -> Result<Vec<Discovery>, String> {
let text = super::journal::read(path)?;
super::fold_text(&normalize(&text, path), &path.display().to_string(), |_, _, _, _| {})
}
pub(super) fn load_indexed(path: &Path) -> Result<Vec<Discovery>, String> {
#[cfg(not(target_arch = "wasm32"))]
let key = super::snapshot::key(path);
let all = load(path)?;
#[cfg(not(target_arch = "wasm32"))]
if let Some(key) = &key {
super::snapshot::store(path, key, &all);
}
Ok(all)
}
pub(super) fn scoped(path: &Path, scope: &super::eligibility::Scope, now: u64) -> Vec<Discovery> {
#[cfg(not(target_arch = "wasm32"))]
if let Some((all, _, _)) = super::snapshot::key(path).and_then(|k| super::snapshot::open(path, &k, scope, now)) {
return all;
}
match load_indexed(path) {
Ok(all) => all.into_iter().filter(|d| super::eligibility::scope_check(&d.meta, scope, now).is_ok()).collect(),
Err(e) => {
eprintln!("instinct: project bank {} not used ({e})", path.display());
Vec::new()
}
}
}
pub(super) fn mentions(path: &Path, needle: &str) -> bool {
std::fs::read_to_string(path).map_or(true, |t| t.contains(needle))
}
pub(super) fn has_lesson(path: &Path, id: &str) -> bool {
let Ok(text) = super::journal::read(path) else { return false };
text.lines().filter(|l| l.contains(id)).any(|l| {
parse_json(l).is_ok_and(|v| {
matches!(v.get("kind").and_then(Json::as_str), Some("discovery" | "machine_discovery"))
&& v.get("id").and_then(Json::as_str) == Some(id)
})
})
}
pub(super) fn event_key() -> String {
#[cfg(not(target_arch = "wasm32"))]
let salt = {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos() as u64)
.unwrap_or(0);
(nanos << 20) ^ ((std::process::id() as u64) << 4) ^ SEQ.fetch_add(1, Ordering::Relaxed)
};
#[cfg(target_arch = "wasm32")]
let salt = SEQ.fetch_add(1, Ordering::Relaxed);
format!("team:{}-{salt:x}", super::now_secs())
}
fn root_of(start: &Path) -> PathBuf {
start
.ancestors()
.find(|d| d.join(".git").exists())
.unwrap_or(start)
.to_path_buf()
}
pub(super) fn ensure_ignore(bank: &Path) {
if let Some(dir) = bank.parent() {
let p = dir.join(".gitignore");
let mut text = std::fs::read_to_string(&p).unwrap_or_default();
let before = text.len();
for pat in IGNORED {
if !text.lines().any(|l| l.trim() == pat) {
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
text.push_str(pat);
text.push('\n');
}
}
if text.len() != before {
let _ = std::fs::write(p, text);
}
}
}
pub(super) fn init(start: &Path) -> Result<String, String> {
let root = root_of(start);
let dir = root.join(DIR);
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
let write = |p: PathBuf, text: &str| std::fs::write(&p, text).map_err(|e| format!("cannot write {}: {e}", p.display()));
let attr = dir.join(".gitattributes");
match std::fs::read_to_string(&attr) {
Ok(t) if t.lines().any(|l| l.split_whitespace().eq(["lessons.jsonl", "merge=union"])) => {}
Ok(t) => write(attr, &format!("{}{}{ATTRIBUTES}", t, if t.is_empty() || t.ends_with('\n') { "" } else { "\n" }))?,
Err(_) => write(attr, ATTRIBUTES)?,
}
ensure_ignore(&dir.join(FILE));
let bank = dir.join(FILE);
if !bank.exists() {
write(bank.clone(), "")?;
}
Ok(format!(
"project bank ready: {}\nnext: git add {DIR} && git commit; teammates get it on pull; bank with `instinct bank --team ...`",
bank.display()
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rows_do_not_depend_on_file_order_and_repeats_collapse() {
let d = r#"{"kind":"discovery","id":"in-a","ts":5}"#;
let h = r#"{"kind":"hit","id":"in-a","ts":9,"outcome_id":"k"}"#;
let p = Path::new("x");
let one = normalize(&format!("{d}\n{h}\n"), p);
assert_eq!(one, normalize(&format!("{h}\n{d}\n{h}\n{d}\n"), p));
assert!(one.starts_with(d));
}
#[test]
fn walk_stops_at_the_git_root_and_at_home() {
let base = std::env::temp_dir().join(format!("instinct-team-unit-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let deep = base.join("repo").join("a").join("b");
std::fs::create_dir_all(&deep).unwrap();
std::fs::create_dir_all(base.join(DIR)).unwrap();
std::fs::write(base.join(DIR).join(FILE), "").unwrap();
std::fs::create_dir_all(base.join("repo").join(".git")).unwrap();
assert_eq!(find_from(&deep, None), None);
std::fs::create_dir_all(base.join("repo").join(DIR)).unwrap();
std::fs::write(base.join("repo").join(DIR).join(FILE), "").unwrap();
assert_eq!(find_from(&deep, None), Some(base.join("repo").join(DIR).join(FILE)));
assert_eq!(find_from(&base, Some(&base)), None);
let _ = std::fs::remove_dir_all(&base);
}
}