instinct-cli 0.3.9

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
# Task-oriented decision workflows with explicit sample and live sources.
AAC # use super::{eligibility, parse_json, recall_methods, Json}
AAC # use std::path::PathBuf

TAC # const MODES: &[(&str, &str)] = &[
TAC # ("start", "Choose a first move"), ("options", "Compare available methods"),
TAC # ("challenge", "Find what could invalidate a method"), ("explain", "Inspect the evidence behind a choice"),
TAC # ("rehearse", "See which lessons survive a changed brief"), ("transfer", "Design a test in a different setting"),
TAC # ("verify", "Compare an expectation with an observation"), ("retry", "Recover one check after a correction"),
TAC # ("handoff", "Prepare a compact card for another agent"), ("debrief", "Draft feedback after an attempt")];

AAA # fn field<'a>(v: &'a Json, key: &str) -> &'a str
TAC # v.get(key).and_then(Json::as_str).unwrap_or("")
TTT # end

AAA # fn scenarios() -> Result<Vec<Json>, String>
TAC # match parse_json(include_str!("../skills/instinct/references/scenarios.json"))? {
TAC # Json::Arr(rows) => Ok(rows), _ => Err("invalid built-in scenarios".into()) }
TTT # end

AAA # fn obj(fields: Vec<(&str, Json)>) -> Json
TAC # Json::Obj(fields.into_iter().map(|(k,v)| (k.to_string(),v)).collect())
TTT # end

AAA # fn txt(value: &str) -> Json
TAC # Json::Str(value.into())
TTT # end

AAA # fn live(path: &PathBuf, q: &str, scope: &eligibility::Scope) -> Result<Vec<Json>, String>
AAC # let matches = recall_methods(path,q,3,scope)?
TAC # Ok(matches.iter().map(|d| { let mut card=vec![
TAC # ("id",txt(&d.id)),("when",txt(&d.when)),("method",txt(&d.how)),("observed",txt(&d.found)),
TAC # ("evidence",txt(&d.evidence)),("exception",txt(&d.reconsider)),("proven",Json::Bool(d.proven_in_use())),
TAC # ("scope",obj(vec![("project",txt(&d.meta.project)),("persona",txt(&d.meta.persona)),("machine",txt(&d.meta.machine)),("harness",txt(&d.meta.harness)),("harness_version",txt(&d.meta.version))])),
TAC # ("hits",Json::Num(d.hits.into())),("misses",Json::Num(d.misses.into()))];
TAC # if let Some(book)=d.casebook.as_ref().filter(|_|d.standing.is_none()) {card.push(("case_check",txt(&book.first_guidance())));}
TAC # obj(card) }).collect())
TTT # end

AAA # fn sample_cards(case: &Json, changed: bool) -> Vec<Json>
AAC # let methods: &[&str] = if changed { &["adapt"] } else { &["move","alternative"] }
TAC # methods.iter().map(|k| obj(vec![("id",txt(k)),("when",txt(field(case,if changed {"changed"} else {"task"}))),
TAC # ("method",txt(field(case,k))),("exception",txt(if changed {""} else {field(case,"exception")})),("evidence",txt("Illustrative example")),
TAC # ("observed",Json::Null),("proven",Json::Bool(false)),("hits",Json::Num(0.0)),("misses",Json::Num(0.0))])).collect()
TTT # end

# Inspect one eligible personal casebook. Experiment selection never records a successful reuse.
AAA # fn experiment(path: &std::path::PathBuf, request: &Json, scope: &eligibility::Scope) -> Result<Json,String>
TAC # let Json::Obj(fields) = request else { return Err("experiment expects an object".into()); };
AAC # let mut seen = std::collections::BTreeSet::new()
AGA # for (key,value) in fields
CAA # if !seen.insert(key)
AAC # return Err(format!("duplicate experiment field {key}"))
TTT # end
TAC # match key.as_str() {
TAC # "facts" | "pool" => (),
TAC # "mode" | "id" | "after_ref" | "project" | "persona" | "harness" | "harness_version" | "machine" if value.as_str().is_some() => (),
TAC # _ => return Err(format!("unexpected or invalid experiment field {key}")),
TAC # }
TTT # end
AAC # let id = field(request,"id")
CAA # if id.trim().is_empty()
AAC # return Err("guide experiment requires a lesson id".into())
TTT # end
AAC # let missing = "no eligible personal casebook for this id and scope"
AAC # let lesson = super::load_user_scoped(path, scope, super::now_secs())?.into_iter().find(|d| d.id == id).ok_or(missing)?
CAA # if lesson.meta.source != "banked" || lesson.standing.is_some() || eligibility::quiet(lesson.hits,lesson.misses) || super::quiet_ids(path).contains(id)
AAC # return Err(missing.into())
TTT # end
AAC # let book = lesson.casebook.as_ref().ok_or(missing)?
AAC # let mut result = super::case_experiment::experiment(book, request.get("facts"), request.get("pool"), request.get("after_ref").and_then(Json::as_str))?
CAA # if let Json::Obj(fields) = &mut result
AAC # fields.push(("mode".into(),txt("experiment")))
AAC # fields.push(("lesson_id".into(),txt(id)))
TTT # end
TAC # Ok(result)
TTT # end

AAA # pub(super) fn run(bank: impl Fn() -> Result<PathBuf,String>, request: &Json, scope: &eligibility::Scope) -> Result<Json,String>
AAC # let mut cache = std::collections::HashMap::new()
AAC # let mode = field(request,"mode")
CAA # if mode == "experiment"
AAC # return experiment(&bank()?,request,scope)
TTT # end
CAA # if ["pool","facts","id","after_ref"].iter().any(|key| request.get(key).is_some())
AAC # return Err("id, facts and pool require guide experiment".into())
TTT # end
CAA # if mode!="run" && request.get("steps").is_some()
AAC # return Err("--steps requires guide run".into())
TTT # end
TAC # let recipe = match mode { "prepare"=> "start,options,challenge", "investigate"=>"explain,rehearse,transfer",
TAC # "review"=>"verify,debrief,handoff", "run"=>field(request,"steps"), _=>return one(&bank,request,scope,&mut cache) };
AAC # let steps:Vec<_> = recipe.split(',').map(str::trim).collect()
AAC # let mut seen=std::collections::HashSet::new()
CAA # if steps.len()>MODES.len() || steps.iter().any(|s|!MODES.iter().any(|(m,_)|m==s)||!seen.insert(*s))
AAC # return Err("select one to ten distinct workflow names from guide list".into())
TTT # end
AAC # let Json::Obj(fields)=request else {return Err("expected guide request".into())}
AAC # let mut reports=Vec::new()
AGA # for step in steps
AAC # let mut inputs:Vec<_>=fields.iter().filter(|(k,_)| k!="steps" && k!="mode").cloned().collect()
AAC # inputs.push(("mode".into(),txt(step)))
AAC # reports.push(one(&bank,&Json::Obj(inputs),scope,&mut cache)?)
TTT # end
TAC # Ok(obj(vec![("mode",txt(mode)),("reports",Json::Arr(reports))]))
TTT # end

AAA # fn one(bank: &impl Fn() -> Result<PathBuf,String>, request: &Json, scope: &eligibility::Scope, cache: &mut std::collections::HashMap<String,Vec<Json>>) -> Result<Json,String>
AAC # let fields = match request { Json::Obj(fields) => fields, _ => return Err("supply a guide request object".into()) }
AGA # for (key,value) in fields
CAA # if !matches!(value,Json::Str(_))
AAC # return Err(format!("guide field {key} must be a string"))
TTT # end
TTT # end
AAC # let mode = field(request,"mode")
CAA # if mode.is_empty() || mode == "list"
AAC # let modes = MODES.iter().map(|(name,purpose)| obj(vec![("name",txt(name)),("purpose",txt(purpose))])).collect()
AAC # let examples = scenarios()?.iter().map(|v| txt(field(v,"name"))).collect()
AAC # return Ok(obj(vec![("modes",Json::Arr(modes)),("examples",Json::Arr(examples)),("experiment",txt("Choose a teaching case for one banked lesson with two observed actions")),("recipes",Json::Arr(["prepare","investigate","review"].iter().map(|s|txt(s)).collect()))]))
TTT # end
CAA # if !MODES.iter().any(|(m,_)| *m==mode)
AAC # return Err(format!("unknown workflow {mode}. Use guide list"))
TTT # end
AAC # let example = field(request,"example")
TAC # let sample = if example.is_empty() { None } else {
TAC # if ["q","changed","expected","observed","correction","method","test","prediction","exception"].iter().any(|k| request.get(k).is_some()) {return Err("use either an example or your own inputs".into());}
TAC # Some(scenarios()?.into_iter().find(|row| field(row,"name")==example).ok_or("unknown example. Use guide list")?) };
AAC # let input = |key| sample.as_ref().and_then(|row|row.get(match key {"q"=>"task","method"=>"move","test"=>"adapt",other=>other})).or_else(||request.get(key)).and_then(Json::as_str)
AAC # let q = input("q").filter(|s|!s.trim().is_empty()).ok_or("guide requires a task via --q or --example")?
AAC # let changed = input("changed").unwrap_or("")
CAA # if matches!(mode,"rehearse"|"transfer") && (changed.trim().is_empty() || changed.trim()==q.trim())
AAC # return Err("supply a different target situation via --changed".into())
TTT # end
AAC # let mut facts = Vec::new()
AAC # let mut lines = Vec::new()
AAC # let mut status = "ready"
TAC # let mut lookup = |task: &str, changed: bool| match &sample {
TAC # Some(row) => Ok(sample_cards(row,changed)), None => {
TAC # if let Some(cards)=cache.get(task){return Ok::<_,String>(cards.clone());}
TAC # let cards=live(&bank()?,task,scope)?;cache.insert(task.into(),cards.clone()); Ok(cards) } };
CAA # if matches!(mode,"verify"|"debrief")
AAC # let expected = input("expected").ok_or("supply the expected result via --expected")?
AAC # facts.push(("expected",txt(expected)))
CAA # if let Some(actual) = input("observed")
AAC # facts.push(("observed",txt(actual)))
AAC # status = if expected==actual {"match"} else {"mismatch"}
AAC # lines.push(format!("Expected {expected:?}; observed {actual:?}."))
CAA # if mode=="debrief"
AAC # lines.push(if expected==actual {"Record a hit only if the method contributed to this result."} else {"Identify which assumption failed before attributing a miss to the method."}.into())
CAA # if let Some(method)=input("method").filter(|s|!s.trim().is_empty())
AAC # facts.push(("lesson_draft",obj(vec![("when",txt(q)),("method_tried",txt(method)),("expected",txt(expected)),("observed",txt(actual)),("reconsider_if",input("exception").map_or(Json::Null,txt))])))
AAC # lines.push(format!("Method tried: {method}"))
TAC # } else {
AAC # lines.push("Add the method you tried to draft a reusable lesson.".into())
TTT # end
AAC # facts.push(("feedback_recorded",Json::Bool(false)))
TTT # end
TAC # } else {
AAC # status="awaiting_observation"
AAC # lines.push(format!("Collect a current result to compare with {expected:?}."))
TTT # end
TAC # } else if mode=="retry" {
AAC # let correction = if sample.is_some() {"That's still wrong."} else {input("correction").filter(|s|!s.trim().is_empty()).ok_or("supply the current user correction via --correction")?}
TAC # let packet = match &sample {Some(row)=>Some(obj(vec![("check",txt(field(row,"check")))])),
TAC # None=>{let raw=super::premortem(&bank()?,correction,Some(q),scope)?; if raw.is_empty(){None}else{Some(parse_json(&raw)?)} }};
CAA # if let Some(p) = packet
AAC # lines.push(field(&p,"check").into())
AAC # facts.push(("check",p))
TAC # } else {
AAC # status="abstained"
AAC # lines.push("No single proven check fits this correction.".into())
TTT # end
TAC # } else {
AAC # let cards = lookup(q,false)?
AAC # let first = cards.first()
CAA # if first.is_none()
AAC # status="no_lesson"
TTT # end
TAC # match mode {
TAC # "start" => if let Some(c)=first {
TAC # lines.push(c.get("case_check").and_then(Json::as_str).unwrap_or(field(c,"method")).into()); facts.push(("choice",c.clone()));
TAC # if c.get("proven")!=Some(&Json::Bool(true)){lines.push("Try this as a candidate and check the result.".into());}
TAC # } else {lines.push("Start with the smallest observable result the user needs.".into());},
TAC # "options" => {
TAC # let mut seen=std::collections::HashSet::new();
TAC # let choices:Vec<_>=cards.iter().filter(|c|seen.insert(field(c,"method"))).cloned().collect();
TAC # for c in &choices {lines.push(format!("{} — applies when {}",field(c,"method"),field(c,"when")));}
TAC # if choices.is_empty(){lines.push("No banked methods fit this brief.".into());}
TAC # facts.push(("options",Json::Arr(choices))); },
TAC # "challenge" => {
TAC # let boundaries:Vec<_>=cards.iter().filter(|c|!field(c,"exception").is_empty()).map(|c|obj(vec![("id",txt(field(c,"id"))),("method",txt(field(c,"method"))),("exception",txt(field(c,"exception")))])).collect();
TAC # for b in &boundaries {lines.push(format!("{} Reconsider if this applies: {}",field(b,"method"),field(b,"exception")));}
TAC # if boundaries.is_empty(){status="missing_boundary";lines.push("Identify one observation that would make you abandon the proposed method.".into());}
TAC # facts.push(("boundaries",Json::Arr(boundaries))); },
TAC # "explain" => if let Some(c)=first {
TAC # lines.push(format!("{} — {}",field(c,"method"),field(c,"evidence")));
TAC # if let Some(obs)=c.get("observed").and_then(Json::as_str){lines.push(format!("Previously observed: {obs}"));}
TAC # facts.push(("evidence_card",c.clone()));
TAC # } else {lines.push("No scoped evidence supports a banked method for this task.".into());},
TAC # "rehearse" | "transfer" => {
TAC # let next=lookup(changed,true)?;
TAC # facts.push(("target",txt(changed)));
TAC # if mode=="rehearse" { status="compared";
TAC # for (label,a,b) in [("retained",&cards,&next),("dropped",&cards,&next),("introduced",&next,&cards)] {
TAC # let subset:Vec<_>=a.iter().filter(|c|b.iter().any(|d|field(c,"id")==field(d,"id"))==(label=="retained")).cloned().collect();
TAC # lines.push(format!("{label}: {}", if subset.is_empty(){"none".into()}else{subset.iter().map(|c|field(c,"method")).collect::<Vec<_>>().join(" / ")}));facts.push((label,Json::Arr(subset))); }
TAC # } else {
TAC # status=if first.is_some(){"hypothesis"}else{"no_source_lesson"};
TAC # if let Some(c)=first {facts.push(("source_lesson",c.clone()));lines.push(format!("Test whether this move transfers: {}",field(c,"method")));}
TAC # else {lines.push("Find a source case with an observed outcome before proposing a transfer.".into());}
TAC # if let Some(check)=first.and_then(|c|c.get("case_check")).and_then(Json::as_str){lines.push(check.into());}
TAC # lines.push(format!("Target task: {changed}")); if input("prediction").is_none(){lines.push("Name a prediction that could turn out wrong.".into());}
TAC # if let Some(test)=input("test") {facts.push(("test",txt(test)));lines.push(format!("Test: {test}"));}
TAC # if let Some(prediction)=input("prediction") {facts.push(("prediction",txt(prediction)));lines.push(format!("Prediction: {prediction}"));}
TAC # if let Some(c)=first {let known=next.iter().any(|d|field(d,"id")==field(c,"id"));
TAC # facts.push(("source_also_retrieved_for_target",Json::Bool(known)));
TAC # facts.push(("hypothesis",txt(&format!("Applying '{}' to '{}' may reproduce the relevant part of the earlier outcome.",field(c,"method"),changed))));
TAC # if !field(c,"exception").is_empty(){lines.push(format!("Check the source boundary: {}",field(c,"exception")));}
TAC # }
TAC # facts.push(("target_lessons",Json::Arr(next))); } },
TAC # "handoff" => {
TAC # lines.push(format!("Task: {q}"));
TAC # if let Some(c)=first {lines.push(format!("Try: {}",field(c,"method")));lines.push(format!("Prior evidence: {}",field(c,"evidence")));
TAC # if !field(c,"exception").is_empty(){lines.push(format!("Reconsider if: {}",field(c,"exception")));} facts.push(("lesson_id",txt(field(c,"id")))); if let Some(scope)=c.get("scope"){facts.push(("scope",scope.clone()));} if c.get("proven")!=Some(&Json::Bool(true)){lines.push("Treat this method as a candidate.".into());}}
TAC # else {lines.push("No prior method selected.".into());}
TAC # if let (Some(expected),Some(observed))=(input("expected"),input("observed")) {
TAC # let state=if expected==observed {"match"} else {"mismatch"};
TAC # facts.push(("current_comparison",obj(vec![("status",txt(state)),("expected",txt(expected)),("observed",txt(observed))])));
TAC # lines.push(format!("Current observation: expected {expected:?}; observed {observed:?}."));
TAC # if expected!=observed {lines.push("Still open: resolve the discrepancy and repeat the check.".into());}
TAC # } else {lines.push("Still open: verify the current outcome.".into());} },
TAC # _=>unreachable!() }
TTT # end
TAC # Ok(obj(vec![("mode",txt(mode)),("task",txt(q)),("source",txt(if sample.is_some(){"example"}else{"live"})),("status",txt(status)),
TAC # ("steps",Json::Arr(lines.into_iter().map(Json::Str).collect())),("details",obj(facts))]))
TTT # end

AAA # pub(super) fn display(packet: &Json) -> String
CAA # if field(packet,"mode") == "experiment"
AAC # return super::json_out(packet)
TTT # end
CAA # if let Some(Json::Arr(reports))=packet.get("reports")
AAC # return reports.iter().map(display).collect::<Vec<_>>().join("\n\n")
TTT # end
CAA # if let Some(Json::Arr(modes)) = packet.get("modes")
AAC # let mut rows:Vec<_>=modes.iter().map(|m|format!("{:10} {}",field(m,"name"),field(m,"purpose"))).collect()
CAA # if let Some(Json::Arr(names))=packet.get("examples")
AAC # rows.push(format!("Examples: {}",names.iter().filter_map(Json::as_str).collect::<Vec<_>>().join(", ")))
TTT # end
AAC # rows.push("experiment Choose a teaching case for a two-action lesson with --id ID".into())
AAC # rows.push("Recipes: prepare, investigate, review. Choose your own with guide run --steps start,challenge,handoff".into())
AAC # rows.push("Try: instinct guide challenge --example shared-document".into())
AAC # return rows.join("\n")
TTT # end
AAC # let mut lines = vec![format!("{} · {} · {}",field(packet,"mode"),field(packet,"source"),field(packet,"status"))]
CAA # if field(packet,"source")=="example" && field(packet,"mode")!="handoff"
AAC # lines.push(field(packet,"task").into())
TTT # end
CAA # if let Some(Json::Arr(steps))=packet.get("steps")
AAC # lines.extend(steps.iter().filter_map(Json::as_str).map(str::to_string))
TTT # end
TAC # lines.join("\n")
TTT # end

# A self-contained, offline field guide of native example results. No personal bank is available.
AAA # pub(super) fn book() -> Result<String,String>
AAC # let scope=eligibility::env_scope()
AAC # let no_bank=||Err("the guidebook cannot read a bank".to_string())
AAC # let mut data=match run(no_bank,&obj(vec![]),&scope)? {Json::Obj(fields)=>fields,_=>unreachable!()}
AAC # let mut examples=Vec::new()
AGA # for row in scenarios()?
AAC # let name=field(&row,"name")
AAC # let mut modes=Vec::new()
AGA # for (mode,_) in MODES
AAC # let report=run(no_bank,&obj(vec![("mode",txt(mode)),("example",txt(name))]),&scope)?
AAC # modes.push((mode.to_string(),report))
TTT # end
AAC # examples.push((name.to_string(),Json::Obj(modes)))
TTT # end
AAC # data.push(("reports".into(),Json::Obj(examples)))
AAC # let data=super::json_out(&Json::Obj(data)).replace('<',"\\u003c").replace('>',"\\u003e").replace('&',"\\u0026")
TAC # Ok(include_str!("guidebook.html").replacen("__GUIDE_DATA__", &data, 1))
TTT # end