From c4e91e1cbeb0e2faa587238ab504c86675b0d916 Mon Sep 17 00:00:00 2001 From: docwilde Date: Sat, 21 Nov 2026 17:03:09 -0700 Subject: [PATCH] feat: record tool outcomes as local evidence Record provider-reported tool success and failure by default through Claude Code, Codex, Antigravity and DOXA. Store deduplicated metadata locally and let reviewers link observations to beliefs and exact learned recipe revisions. Set `LORE_TOOL_EVIDENCE=0` to turn recording off. --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- CHANGELOG.md | 6 + Cargo.lock | 2 +- README.md | 7 +- antigravity/hooks.json | 17 ++ antigravity/plugin.json | 6 + bin/lore | 2 +- codex/hooks/hooks.json | 11 + docs/tool-evidence.md | 31 ++ hooks/hooks.json | 22 ++ plugin.json | 2 +- rust/lore-core/Cargo.toml | 2 +- rust/lore-core/src/core.rs | 2 + rust/lore-core/src/lib.rs | 1 + rust/lore-core/src/standalone.rs | 35 ++- rust/lore-core/src/tool_evidence.rs | 409 ++++++++++++++++++++++++++ rust/lore-core/tests/tool_evidence.rs | 156 ++++++++++ 18 files changed, 707 insertions(+), 8 deletions(-) create mode 100644 antigravity/hooks.json create mode 100644 antigravity/plugin.json create mode 100644 docs/tool-evidence.md create mode 100644 rust/lore-core/src/tool_evidence.rs create mode 100644 rust/lore-core/tests/tool_evidence.rs diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 5a7d352..c76c16c 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "lore", "source": "./", "description": "Shared memory for Claude Code, Codex, and DOXA: capped curated facts, evidence-backed beliefs, FTS5 session search, staged review, learned skills, and signed sync.", - "version": "0.62.31" + "version": "0.62.32" } ] } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index f497054..9c47b54 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "lore", "description": "Memory for Claude Code that reasons about you and improves itself: Honcho-pattern belief store with deriver, dreamer and dialectic (/lore:ask), automatic skillification with a closed judge/update/retire loop, on a Hermes-pattern core \u2014 hard-capped curated memory, FTS5 session search, staged review.", - "version": "0.62.31", + "version": "0.62.32", "author": { "name": "Fabian Wilde", "email": "docwilde@proton.me" diff --git a/CHANGELOG.md b/CHANGELOG.md index 823ddc3..100b72b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 0.62.32 — 2026-11-21 + +- Record provider-reported tool outcomes by default in Claude Code, Codex, Antigravity and DOXA. +- Store deduplicated observations locally and let reviewers link them to beliefs and exact learned recipe revisions. +- Set `LORE_TOOL_EVIDENCE=0` to turn recording off. + ## 0.62.31 — 2026-11-19 - Document LORE memory injection and local transcript indexing for Antigravity sessions in DOXA. diff --git a/Cargo.lock b/Cargo.lock index 4d53b4e..360989c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -612,7 +612,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "lore-core" -version = "0.62.31" +version = "0.62.32" dependencies = [ "fancy-regex", "hmac", diff --git a/README.md b/README.md index 2d98e0e..d723342 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,10 @@ and relations between beliefs do not turn them into approved facts. ## What you get +[LORE 0.62.32](https://github.com/docwilde/LORE/releases/tag/v0.62.32) records +tool outcomes by default and lets reviewers link them to beliefs and learned +recipes. + [LORE 0.62.31](https://github.com/docwilde/LORE/releases/tag/v0.62.31) documents shared memory for Gemini sessions through Google Antigravity in DOXA. @@ -46,6 +50,7 @@ paged pending review, protected cleanup, and optional shared skill usage. while preserving human review of each complete, exact proposal. - **Reviewed cleanup.** [Preview diagnostic retention and select orphaned codegraph snapshots](docs/retention.md) before applying a reviewed plan. +- **Tool evidence.** LORE [captures reported tool outcomes](docs/tool-evidence.md) by default. Link relevant observations to beliefs and learned recipes. - **Learned skills.** Recipes carry outcome history and staged updates or retirement. - **Local skill experiments.** [Compare exact pending coding skills](docs/skill-evaluation.md) against frozen tests before human approval. The experimental subscription @@ -111,7 +116,7 @@ This WSL 2 setup has not been verified in LORE CI; see the ### Codex LORE supports Codex through the portable [`plugin.json`](plugin.json) and -its [startup and prompt hooks](codex/hooks/hooks.json). Enable the full plugin, +its [startup, prompt and tool hooks](codex/hooks/hooks.json). Enable the full plugin, then review and trust its hooks with `/hooks` in Codex. Once trusted, the startup hook injects the shared user and current project snapshot at startup, resume, clear, compaction, and fork. Codex requires a new review when a hook changes; see its diff --git a/antigravity/hooks.json b/antigravity/hooks.json new file mode 100644 index 0000000..6334fa7 --- /dev/null +++ b/antigravity/hooks.json @@ -0,0 +1,17 @@ +{ + "lore-tool-evidence": { + "enabled": true, + "PostToolUse": [ + { + "matcher": ".*", + "hooks": [ + { + "type": "command", + "command": "if [ \"${LORE_TOOL_EVIDENCE:-1}\" != 0 ] && [ -z \"${LORE_SKIP:-}\" ]; then exec lore-rs tool-evidence hook --engine antigravity --event PostToolUse; else printf '%s\\n' '{}'; fi", + "timeout": 2 + } + ] + } + ] + } +} diff --git a/antigravity/plugin.json b/antigravity/plugin.json new file mode 100644 index 0000000..f1a717f --- /dev/null +++ b/antigravity/plugin.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://antigravity.google/schemas/v1/plugin.json", + "name": "lore-tool-evidence", + "version": "0.62.32", + "description": "Record reported tool outcomes in the local LORE evidence store." +} diff --git a/bin/lore b/bin/lore index 172ba2d..c723a7b 100755 --- a/bin/lore +++ b/bin/lore @@ -49,7 +49,7 @@ fingerprint=$({ find "$root/rust/lore-core/src" -type f -exec sha256sum {} +; sh target=$cache/$fingerprint binary=$target/release/lore-rs if matches "$binary"; then exec "$binary" "$@"; fi -if [ "${1:-}" = hook ]; then +if [ "${1:-}" = hook ] || { [ "${1:-}" = tool-evidence ] && [ "${2:-}" = hook ]; }; then printf 'LORE native carrier is not installed; run the LORE setup command once.\n' >&2 exit 1 fi diff --git a/codex/hooks/hooks.json b/codex/hooks/hooks.json index 5e1a12b..f9a2e1c 100644 --- a/codex/hooks/hooks.json +++ b/codex/hooks/hooks.json @@ -26,6 +26,17 @@ } ] } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "if [ \"${LORE_TOOL_EVIDENCE:-1}\" != 0 ] && [ -z \"${LORE_SKIP:-}\" ]; then exec \"${PLUGIN_ROOT}/bin/lore\" tool-evidence hook --engine codex --event PostToolUse; else printf '%s\\n' '{}'; fi", + "timeout": 2 + } + ] + } ] } } diff --git a/docs/tool-evidence.md b/docs/tool-evidence.md new file mode 100644 index 0000000..1a70eb6 --- /dev/null +++ b/docs/tool-evidence.md @@ -0,0 +1,31 @@ +# Tool evidence + +Tool recording is on by default. Each observation records the provider, project, session, call ID, tool name and reported outcome. LORE stores these observations locally and deduplicates repeated deliveries of the same call. Hook arguments, command output and error text stay out of the evidence store. Set **LORE_TOOL_EVIDENCE=0** in the environment that launches the agent to turn recording off. + +## Provider support + +| Harness | Source of outcome | +| --- | --- | +| Claude Code | The LORE plugin registers **PostToolUse** and **PostToolUseFailure**. | +| Codex | The plugin registers **PostToolUse**. LORE uses a structured exit code or the MCP result’s error flag. Codex shell hooks that supply output alone produce no observation. | +| Antigravity | The companion plugin uses **PostToolUse**, which reports success or failure in its **error** field. LORE uses the conversation and step IDs to identify each call. | +| DOXA | The daemon records structured tool results from Claude, Codex, Antigravity, DeepSeek and GLM. Router observations carry the active worker engine. DOXA writes up to 128 observations at the end of each turn. | + +For Antigravity, build and install the LORE CLI from this checkout with **./task install**, then run **agy plugin install "$PWD/antigravity"**. Launch Antigravity with **lore-rs** on **PATH**. The companion plugin records tool evidence. DOXA supplies LORE memory to its own Antigravity sessions. + +DOXA uses its embedded LORE core when it supports tool evidence. A build with an older core looks for an updated **lore-rs** on **PATH**. Set **DOXA_LORE_RS** to an absolute path to select the executable explicitly. **DOXA_LORE=0** also disables recording for that DOXA session. + +## Review and link observations + +Use **lore tool-evidence list** from the relevant project. Results are newest first. Pass **--before ID** to read the next page. In a human terminal, attach a reviewed observation to a belief or learned recipe: + +~~~sh +lore tool-evidence link 42 --belief 7 +lore tool-evidence link 42 --recipe verify-build +lore tool-evidence list --belief 7 +lore tool-evidence list --recipe verify-build +~~~ + +The link lets you retrieve the tool result with the selected belief or recipe. Each recipe link identifies the exact recipe revision. It carries the provider’s reported success or failure. Belief confidence, belief outcomes and recipe success counters retain their existing review and evaluation paths. + +[Claude Code hooks](https://code.claude.com/docs/en/hooks) · [Codex hooks](https://learn.chatgpt.com/docs/hooks) · [Antigravity hooks](https://antigravity.google/docs/build-plugins/#lifecycle-hooks) diff --git a/hooks/hooks.json b/hooks/hooks.json index 269ce1c..4c57bbf 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -47,6 +47,28 @@ } ] } + ], + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "if [ \"${LORE_TOOL_EVIDENCE:-1}\" != 0 ] && [ -z \"${LORE_SKIP:-}\" ]; then exec \"${CLAUDE_PLUGIN_ROOT}/bin/lore\" tool-evidence hook --engine claude --event PostToolUse; else printf '%s\\n' '{}'; fi", + "timeout": 2 + } + ] + } + ], + "PostToolUseFailure": [ + { + "hooks": [ + { + "type": "command", + "command": "if [ \"${LORE_TOOL_EVIDENCE:-1}\" != 0 ] && [ -z \"${LORE_SKIP:-}\" ]; then exec \"${CLAUDE_PLUGIN_ROOT}/bin/lore\" tool-evidence hook --engine claude --event PostToolUseFailure; else printf '%s\\n' '{}'; fi", + "timeout": 2 + } + ] + } ] } } diff --git a/plugin.json b/plugin.json index bf9042d..96762b3 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "lore", - "version": "0.62.31", + "version": "0.62.32", "description": "Unified user, repo, and session memory for Claude Code, Codex, and DOXA", "author": { "name": "Dr. Fabian Wilde", diff --git a/rust/lore-core/Cargo.toml b/rust/lore-core/Cargo.toml index be6a6ba..3eb3d4b 100644 --- a/rust/lore-core/Cargo.toml +++ b/rust/lore-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lore-core" -version = "0.62.31" +version = "0.62.32" edition = "2021" license = "AGPL-3.0-only" description = "Native LORE memory, beliefs, review and session index" diff --git a/rust/lore-core/src/core.rs b/rust/lore-core/src/core.rs index a287c20..1dcab03 100644 --- a/rust/lore-core/src/core.rs +++ b/rust/lore-core/src/core.rs @@ -30,6 +30,7 @@ impl Core { "codegraph_snapshot_read_v1", "codegraph_snapshot_store_v1", "diagnostic_trace_capture_v1", + "tool_evidence_record_v1", "diagnostic_trace_read_v1", "diagnostic_retention_plan_v1", "diagnostic_retention_apply_v1", @@ -80,6 +81,7 @@ impl Core { let config = &self.config; let auth = &self.authority; let value = match req["op"].as_str().ok_or(Error::InvalidRequest)? { + "tool_evidence_record_v1" => crate::tool_evidence::record(config, req, "doxa")?, "diagnostic_trace_capture_v1" => crate::diagnostics::capture(config, req)?, "diagnostic_trace_read_v1" => crate::diagnostics::show(config, req)?, "diagnostic_retention_plan_v1" => crate::retention::plan(config, req)?, diff --git a/rust/lore-core/src/lib.rs b/rust/lore-core/src/lib.rs index f8de041..0566df4 100644 --- a/rust/lore-core/src/lib.rs +++ b/rust/lore-core/src/lib.rs @@ -8,6 +8,7 @@ pub mod context; mod core; pub mod dream; pub mod diagnostics; +mod tool_evidence; pub mod filemap; pub mod files; pub mod gate; diff --git a/rust/lore-core/src/standalone.rs b/rust/lore-core/src/standalone.rs index daa7972..94a3250 100644 --- a/rust/lore-core/src/standalone.rs +++ b/rust/lore-core/src/standalone.rs @@ -34,6 +34,8 @@ Diagnostics: trace capture --transcript FILE --session-id ID --engine claude|cod trace retention-plan|retention-apply --json REVIEWED_PLAN Administration: setup teardown reset project move config show|set|unset Sync: sync status|health|whoami|push|pull|bootstrap|serve|export|import|classes|login|resign|seed +Tool evidence: tool-evidence list [--belief ID | --recipe NAME] [--before ID] [--limit N] + tool-evidence link OBSERVATION_ID (--belief ID | --recipe NAME) Integration: mcp hook Use --json '{...}' for structured arguments; --cwd defaults to this directory. @@ -260,6 +262,9 @@ fn validate_flags(group: &str, sub: &str, req: &Value) -> Result<()> { ("consult"|"ask"|"dialectic",_) => "query limit", ("outcome",_) => "belief_id event source note", ("skills",_) => "prompt limit pid suite sha256 kind", + ("tool-evidence", "hook") => "engine event", + ("tool-evidence", "list") => "belief recipe before limit", + ("tool-evidence", "link") => "belief recipe", ("trace",_) => "transcript session_id engine sha256 policy plan_sha256 plan", ("codegraph", "cleanup-plan"|"cleanup-apply") => "plan_sha256 plan reviewed_orphan_keys", ("dream",_) => "dry_run engine", @@ -331,7 +336,12 @@ pub fn run(args: &[String]) -> Result<()> { if matches!(args[0].as_str(), "--version" | "version") { return output(json!(env!("CARGO_PKG_VERSION"))); } - let cfg = Config::from_env(Duration::from_secs(3))?; + let timeout = if args[0] == "tool-evidence" && args.get(1).is_some_and(|arg| arg == "hook") { + Duration::from_millis(600) + } else { + Duration::from_secs(3) + }; + let cfg = Config::from_env(timeout)?; if args[0] == "hook" { return hook(&cfg, &args[1..]); } @@ -353,6 +363,7 @@ pub fn run(args: &[String]) -> Result<()> { | "project" | "trace" | "codegraph" + | "tool-evidence" ); let (sub, tail) = if grouped && args.get(1).is_some_and(|s| !s.starts_with('-')) { (args[1].as_str(), &args[2..]) @@ -371,6 +382,28 @@ pub fn run(args: &[String]) -> Result<()> { } let mut core = Core::new(cfg.clone(), auth.clone()); let value = match (group, sub) { + ("tool-evidence", "hook") if p.is_empty() => { + if crate::tool_evidence::enabled(&cfg) { + let mut raw = Vec::new(); + io::stdin() + .lock() + .take(crate::MAX_FRAME_BYTES as u64 + 1) + .read_to_end(&mut raw)?; + if raw.len() > crate::MAX_FRAME_BYTES { + return Err(Error::TooLarge); + } + let input = serde_json::from_slice(&raw).map_err(|_| Error::InvalidRequest)?; + let engine = req["engine"].as_str().ok_or(Error::InvalidRequest)?; + let event = req["event"].as_str().ok_or(Error::InvalidRequest)?; + crate::tool_evidence::hook(&cfg, engine, event, &input)?; + } + json!({}) + } + ("tool-evidence", "list") if p.is_empty() => crate::tool_evidence::list(&cfg, &req)?, + ("tool-evidence", "link") if p.len() == 1 => { + req["observation_id"] = json!(p[0].parse::().map_err(|_| Error::InvalidRequest)?); + crate::tool_evidence::link(&cfg, &req, &auth)? + } ("trace", "retention-plan") => crate::retention::plan(&cfg, &req)?, ("trace", "retention-apply") => crate::retention::apply(&cfg, &req, &auth)?, ("codegraph", "cleanup-plan") => crate::codegraph_snapshot::cleanup_plan(&cfg, &req)?, diff --git a/rust/lore-core/src/tool_evidence.rs b/rust/lore-core/src/tool_evidence.rs new file mode 100644 index 0000000..2302f43 --- /dev/null +++ b/rust/lore-core/src/tool_evidence.rs @@ -0,0 +1,409 @@ +//! Provider-reported tool observations and explicit links to beliefs or recipes. +use crate::{config, gate, scrub, skills, store, Error, Result}; +use rusqlite::{params, OptionalExtension, TransactionBehavior}; +use serde_json::{json, Value}; +use std::path::Path; + +const MAX_BATCH: usize = 128; +const SCHEMA: &str = " + CREATE TABLE IF NOT EXISTS tool_observations ( + id INTEGER PRIMARY KEY, + project TEXT NOT NULL, + source TEXT NOT NULL, + engine TEXT NOT NULL, + session_id TEXT NOT NULL, + call_id TEXT NOT NULL, + tool TEXT NOT NULL, + outcome TEXT NOT NULL CHECK (outcome IN ('success', 'failure')), + recorded_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (project, source, engine, session_id, call_id) + ); + CREATE INDEX IF NOT EXISTS tool_observations_project_id ON tool_observations(project, id); + CREATE TABLE IF NOT EXISTS tool_observation_links ( + observation_id INTEGER NOT NULL REFERENCES tool_observations(id), + target_kind TEXT NOT NULL CHECK (target_kind IN ('belief', 'recipe')), + target_id TEXT NOT NULL, + PRIMARY KEY (observation_id, target_kind, target_id) + );"; + +pub(crate) fn enabled(cfg: &config::Config) -> bool { + cfg.var("LORE_TOOL_EVIDENCE").as_deref() != Ok("0") + && !cfg.var("LORE_SKIP").is_ok_and(|value| !value.is_empty()) +} + +fn token(value: &Value, max: usize) -> Result<&str> { + value + .as_str() + .filter(|s| { + !s.is_empty() + && s.len() <= max + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_-.:/".contains(&b)) + }) + .ok_or(Error::InvalidRequest) +} + +fn project(cwd: &Path) -> Result { + let slug = config::project_slug(cwd); + if slug.len() > 4096 || scrub::scrub(&slug)? != slug { + return Err(Error::InvalidRequest); + } + Ok(slug) +} + +pub(crate) fn record(cfg: &config::Config, req: &Value, source: &str) -> Result { + if !enabled(cfg) { + return Ok(json!({"inserted": 0, "enabled": false})); + } + let cwd = gate::cwd(req)?; + let engine = req["engine"] + .as_str() + .filter(|s| matches!(*s, "claude" | "codex" | "antigravity" | "deepseek" | "glm")) + .ok_or(Error::InvalidRequest)?; + let session = req["session_id"] + .as_str() + .filter(|s| config::valid_id(s)) + .ok_or(Error::InvalidRequest)?; + let input = req["observations"] + .as_array() + .filter(|batch| !batch.is_empty() && batch.len() <= MAX_BATCH) + .ok_or(Error::InvalidRequest)?; + let mut observations = Vec::with_capacity(input.len()); + for item in input { + let id = token(&item["call_id"], 256)?; + let tool = token(&item["tool"], 128)?; + let outcome = item["outcome"] + .as_str() + .filter(|s| matches!(*s, "success" | "failure")) + .ok_or(Error::InvalidRequest)?; + if scrub::scrub(id)? != id || scrub::scrub(tool)? != tool { + return Err(Error::InvalidRequest); + } + observations.push((id, tool, outcome)); + } + if scrub::scrub(session)? != session { + return Err(Error::InvalidRequest); + } + let project = project(cwd)?; + let mut db = store::connect(cfg)?; + db.execute_batch(SCHEMA)?; + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let mut inserted = 0; + for (call_id, tool, outcome) in observations { + let previous = tx + .query_row( + "SELECT tool, outcome FROM tool_observations + WHERE project=? AND source=? AND engine=? AND session_id=? AND call_id=?", + params![project, source, engine, session, call_id], + |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)), + ) + .optional()?; + if let Some((old_tool, old_outcome)) = previous { + if old_tool != tool || old_outcome != outcome { + return Err(Error::Changed); + } + continue; + } + tx.execute( + "INSERT INTO tool_observations(project, source, engine, session_id, call_id, tool, outcome) + VALUES (?, ?, ?, ?, ?, ?, ?)", + params![project, source, engine, session, call_id, tool, outcome], + )?; + inserted += 1; + } + tx.commit()?; + Ok(json!({"inserted": inserted, "enabled": true})) +} + +fn codex_outcome(input: &Value) -> Option<&'static str> { + let response = &input["tool_response"]; + let code = response["exit_code"].as_i64(); + if let Some(code) = code { + return Some(if code == 0 { "success" } else { "failure" }); + } + if input["tool_name"] + .as_str() + .is_some_and(|name| name.starts_with("mcp__")) + && response["content"].is_array() + { + return match response.get("isError") { + None | Some(Value::Bool(false)) => Some("success"), + Some(Value::Bool(true)) => Some("failure"), + _ => None, + }; + } + None +} + +pub(crate) fn hook(cfg: &config::Config, engine: &str, event: &str, input: &Value) -> Result<()> { + if !matches!( + (engine, event), + ("claude", "PostToolUse" | "PostToolUseFailure") | ("codex" | "antigravity", "PostToolUse") + ) { + return Err(Error::InvalidRequest); + } + if engine != "antigravity" && input["hook_event_name"] != event { + return Err(Error::InvalidRequest); + } + let (cwd, session, call_id, tool, outcome) = if engine == "antigravity" { + let paths = input["workspacePaths"] + .as_array() + .filter(|rows| rows.len() == 1) + .ok_or(Error::InvalidRequest)?; + let step = input["stepIdx"].as_u64().ok_or(Error::InvalidRequest)?; + let outcome = match input.get("error") { + None => "success", + Some(Value::String(error)) => { + if error.is_empty() { + "success" + } else { + "failure" + } + } + _ => return Err(Error::InvalidRequest), + }; + ( + &paths[0], + &input["conversationId"], + format!("step-{step}"), + &input["toolCall"]["name"], + outcome, + ) + } else { + let outcome = if engine == "codex" { + let Some(outcome) = codex_outcome(input) else { + return Ok(()); + }; + outcome + } else if event == "PostToolUseFailure" { + "failure" + } else { + "success" + }; + let id = token(&input["tool_use_id"], 192)?.to_owned(); + ( + &input["cwd"], + &input["session_id"], + id, + &input["tool_name"], + outcome, + ) + }; + record( + cfg, + &json!({"cwd":cwd,"engine":engine,"session_id":session, + "observations":[{"call_id":call_id,"tool":tool,"outcome":outcome}]}), + "hook", + )?; + Ok(()) +} + +fn positive(value: &Value) -> Result { + value + .as_i64() + .or_else(|| value.as_str()?.parse().ok()) + .filter(|n| *n > 0) + .ok_or(Error::InvalidRequest) +} + +fn target(cfg: &config::Config, req: &Value) -> Result> { + match (req.get("belief"), req.get("recipe")) { + (Some(id), None) => Ok(Some(("belief", positive(id)?.to_string()))), + (None, Some(recipe)) => { + let name = recipe + .as_str() + .filter(|s| config::valid_id(s)) + .ok_or(Error::InvalidRequest)?; + if !skills::learned(cfg)?.contains_key(name) { + return Err(Error::NoMatch); + } + let bytes = crate::files::read_regular( + &cfg.skills.join(name).join("SKILL.md"), + crate::MAX_FRAME_BYTES, + )?; + Ok(Some(( + "recipe", + format!("{name}@{}", crate::digest(&bytes)), + ))) + } + (None, None) => Ok(None), + _ => Err(Error::InvalidRequest), + } +} + +pub(crate) fn list(cfg: &config::Config, req: &Value) -> Result { + let slug = project(gate::cwd(req)?)?; + let target = target(cfg, req)?; + let limit = req.get("limit").map(positive).transpose()?.unwrap_or(30); + if limit > 100 { + return Err(Error::InvalidRequest); + } + let before = req.get("before").map(positive).transpose()?; + let db = store::connect(cfg)?; + db.execute_batch(SCHEMA)?; + let mut query = db.prepare( + "SELECT id, source, engine, session_id, call_id, tool, outcome, recorded_at + FROM tool_observations + WHERE project=?1 AND (?2 IS NULL OR id < ?2) + AND (?4 IS NULL OR EXISTS ( + SELECT 1 FROM tool_observation_links + WHERE observation_id=tool_observations.id AND target_kind=?4 AND target_id=?5)) + ORDER BY id DESC LIMIT ?3", + )?; + let rows = query.query_map( + params![ + slug, + before, + limit, + target.as_ref().map(|(kind, _)| *kind), + target.as_ref().map(|(_, id)| id) + ], + |row| { + Ok( + json!({"id":row.get::<_, i64>(0)?, "source":row.get::<_, String>(1)?, + "engine":row.get::<_, String>(2)?, "session_id":row.get::<_, String>(3)?, + "call_id":row.get::<_, String>(4)?, "tool":row.get::<_, String>(5)?, + "outcome":row.get::<_, String>(6)?, "recorded_at":row.get::<_, String>(7)?}), + ) + }, + )?; + Ok(json!(rows.collect::, _>>()?)) +} + +pub(crate) fn link( + cfg: &config::Config, + req: &Value, + authority: &gate::Authority, +) -> Result { + authority.require_review()?; + let slug = project(gate::cwd(req)?)?; + let id = positive(&req["observation_id"])?; + let (kind, target) = target(cfg, req)?.ok_or(Error::InvalidRequest)?; + let mut db = store::connect(cfg)?; + db.execute_batch(SCHEMA)?; + let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; + let visible: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM tool_observations WHERE project=? AND id=?)", + params![slug, id], + |row| row.get(0), + )?; + if !visible { + return Err(Error::NoMatch); + } + if kind == "belief" { + let visible: bool = tx.query_row( + "SELECT EXISTS(SELECT 1 FROM beliefs WHERE id=? AND subject IN ('user', 'user-model', ?))", + params![target, format!("project:{slug}")], |row| row.get(0))?; + if !visible { + return Err(Error::NoMatch); + } + } + tx.execute( + "INSERT OR IGNORE INTO tool_observation_links VALUES (?, ?, ?)", + params![id, kind, target], + )?; + tx.commit()?; + Ok(json!({"observation_id":id,"target_kind":kind,"target_id":target})) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn owner_links_stay_scoped_and_preserve_belief_and_recipe_outcomes() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let cfg = config::Config { + root: root.join("lore"), + skills: root.join("skills"), + projects: root.join("projects"), + codex_sessions: root.join("codex"), + user_cap: 9000, + project_cap: 8800, + machine_cap: 3000, + filemap_cap: 4000, + timeout: std::time::Duration::from_secs(1), + sync: config::SyncConfig { + enabled: false, + classes: Default::default(), + key: None, + }, + }; + let recipe = cfg.skills.join("fixture-recipe"); + std::fs::create_dir_all(&recipe).unwrap(); + std::fs::write( + recipe.join("SKILL.md"), + "---\nname: fixture-recipe\ndescription: A fixture\n---\nlore-learned", + ) + .unwrap(); + let slug = project(root).unwrap(); + let db = store::connect(&cfg).unwrap(); + db.execute_batch(SCHEMA).unwrap(); + db.execute( + "INSERT INTO beliefs(id,subject,claim,confidence) VALUES (1,?,'fixture belief',0.5)", + [format!("project:{slug}")], + ) + .unwrap(); + db.execute("INSERT INTO beliefs(id,subject,claim,confidence) VALUES (2,'project:foreign','outside',0.5)", + []).unwrap(); + db.execute( + "INSERT INTO tool_observations(project,source,engine,session_id,call_id,tool,outcome) + VALUES (?,'hook','claude','fixture','test-1','Bash','failure')", + [slug], + ) + .unwrap(); + + let human = gate::Authority::HumanReview { + agent: "fixture".into(), + engine: "human".into(), + }; + for target in [json!({"belief":1}), json!({"recipe":"fixture-recipe"})] { + let mut request = target.clone(); + request["cwd"] = json!(root); + assert_eq!(list(&cfg, &request).unwrap(), json!([])); + request["observation_id"] = json!(1); + for _ in 0..2 { + link(&cfg, &request, &human).unwrap(); + } + let list = list(&cfg, &request).unwrap(); + assert_eq!(list.as_array().unwrap().len(), 1); + assert_eq!(list[0]["outcome"], "failure"); + } + assert_eq!( + link( + &cfg, + &json!({"cwd":root,"observation_id":1,"belief":2}), + &human + ), + Err(Error::NoMatch) + ); + assert_eq!( + db.query_row("SELECT count(*) FROM belief_evidence", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 0 + ); + assert_eq!( + db.query_row("SELECT confidence FROM beliefs WHERE id=1", [], |row| row + .get::<_, f64>( + 0 + )) + .unwrap(), + 0.5 + ); + assert!(!cfg.root.join("skill_usage.json").exists()); + std::fs::write( + recipe.join("SKILL.md"), + "--- +name: fixture-recipe +--- +lore-learned revised", + ) + .unwrap(); + assert_eq!( + list(&cfg, &json!({"cwd":root,"recipe":"fixture-recipe"})).unwrap(), + json!([]) + ); + } +} diff --git a/rust/lore-core/tests/tool_evidence.rs b/rust/lore-core/tests/tool_evidence.rs new file mode 100644 index 0000000..afdc1aa --- /dev/null +++ b/rust/lore-core/tests/tool_evidence.rs @@ -0,0 +1,156 @@ +use serde_json::{json, Value}; +use std::{ + fs, + io::Write, + path::Path, + process::{Command, Stdio}, +}; + +fn cli(root: &Path, recording: Option<&str>) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_lore-rs")); + command + .current_dir(root) + .env_clear() + .env("HOME", root) + .env("LORE_ROOT", root.join("lore")) + .env("LORE_DISABLE_SYNC", "1"); + if let Some(value) = recording { + command.env("LORE_TOOL_EVIDENCE", value); + } + command +} + +fn hook( + root: &Path, + recording: Option<&str>, + engine: &str, + event: &str, + payload: &Value, +) -> std::process::Output { + let mut child = cli(root, recording) + .args([ + "tool-evidence", + "hook", + "--engine", + engine, + "--event", + event, + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + writeln!(child.stdin.take().unwrap(), "{payload}").unwrap(); + child.wait_with_output().unwrap() +} + +#[test] +fn records_structured_completions_once_and_discards_payloads() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let claude = |id: &str, event: &str| { + json!({ + "hook_event_name": event, "cwd": root, "session_id": "claude-session", + "tool_use_id": id, "tool_name": "Bash", "tool_input": {"command":"evidence-test-private-input"}, + "tool_response":"evidence-test-private-output", "error":"evidence-test-private-error", + }) + }; + let first = claude("call-1", "PostToolUse"); + assert!(hook(root, Some("0"), "claude", "PostToolUse", &first) + .status + .success()); + assert!(!root.join("lore/state.db").exists()); + for _ in 0..2 { + assert!(hook(root, None, "claude", "PostToolUse", &first) + .status + .success()); + } + let failure = claude("call-2", "PostToolUseFailure"); + assert!(hook(root, None, "claude", "PostToolUseFailure", &failure) + .status + .success()); + let conflict = claude("call-1", "PostToolUseFailure"); + assert!(!hook(root, None, "claude", "PostToolUseFailure", &conflict) + .status + .success()); + + let codex = |id: &str, tool: &str, response: Value| { + json!({ + "hook_event_name": "PostToolUse", "cwd":root,"session_id":"codex-session", + "tool_use_id":id,"tool_name":tool,"tool_response":response, + }) + }; + for (id, response) in [ + ("mcp-success", json!({"content":[]})), + ("mcp-failure", json!({"content":[],"isError":true})), + ] { + assert!(hook( + root, + None, + "codex", + "PostToolUse", + &codex(id, "mcp__fixture__read", response) + ) + .status + .success()); + } + let opaque = codex("opaque", "Bash", json!("Process exited with code 0")); + assert!(hook(root, None, "codex", "PostToolUse", &opaque) + .status + .success()); + + for (step, error) in [(0, ""), (1, "evidence-test-private-error")] { + let payload = json!({"workspacePaths":[root], "conversationId":"agy-session", + "stepIdx":step,"toolCall":{"name":"run_command","args":{"CommandLine":"evidence-test-private-input"}}, + "error":error}); + let result = hook(root, None, "antigravity", "PostToolUse", &payload); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + assert_eq!( + serde_json::from_slice::(&result.stdout).unwrap(), + json!({}) + ); + } + + let listing = cli(root, None) + .args(["tool-evidence", "list"]) + .output() + .unwrap(); + assert!( + listing.status.success(), + "{}", + String::from_utf8_lossy(&listing.stderr) + ); + let rows: Vec = serde_json::from_slice(&listing.stdout).unwrap(); + assert_eq!( + rows.iter() + .map(|row| ( + row["engine"].as_str().unwrap(), + row["call_id"].as_str().unwrap(), + row["outcome"].as_str().unwrap() + )) + .collect::>(), + [ + ("antigravity", "step-1", "failure"), + ("antigravity", "step-0", "success"), + ("codex", "mcp-failure", "failure"), + ("codex", "mcp-success", "success"), + ("claude", "call-2", "failure"), + ("claude", "call-1", "success"), + ] + ); + let db = fs::read(root.join("lore/state.db")).unwrap(); + assert!(!db + .windows(b"evidence-test-private".len()) + .any(|candidate| candidate == b"evidence-test-private")); + let rejected = cli(root, None) + .args(["tool-evidence", "link", "1", "--belief", "1"]) + .output() + .unwrap(); + assert!(!rejected.status.success()); + assert!(String::from_utf8_lossy(&rejected.stderr).contains("untrusted_write")); +}