From b9913c76540e36ece38051bb4269a8c87bee1484 Mon Sep 17 00:00:00 2001 From: "Dr. Fabian Wilde" Date: Wed, 25 Nov 2026 22:55:51 +0100 Subject: [PATCH 1/2] feat(lore): add standalone Antigravity hooks and AST queries --- Cargo.lock | 99 ++++++++++++++++++++--- README.md | 21 +++-- antigravity/hooks.json | 16 ++++ antigravity/plugin.json | 2 +- docs/manual.md | 19 +++++ docs/tool-evidence.md | 2 +- rust/lore-core/Cargo.toml | 1 + rust/lore-core/src/context.rs | 3 + rust/lore-core/src/index.rs | 104 +++++++++++++++++++++++++ rust/lore-core/src/scrub.rs | 27 ++++++- rust/lore-core/src/standalone.rs | 54 +++++++++++-- rust/lore-core/src/standalone_hooks.rs | 55 ++++++++++++- rust/lore-core/tests/cli.rs | 102 +++++++++++++++++++++++- 13 files changed, 474 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2c7f320..65b5482 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -157,9 +157,31 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] +[[package]] +name = "doxa-codegraph" +version = "2.0.0-beta.90" +source = "git+https://github.com/docwilde/doxa?rev=fa763acc8e738f461cd2f15ea8adfd8d58020328#fa763acc8e738f461cd2f15ea8adfd8d58020328" +dependencies = [ + "libc", + "proc-macro2", + "ring", + "serde", + "serde_json", + "sha2", + "syn 2.0.119", + "tree-sitter", + "tree-sitter-python", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.14" @@ -552,6 +574,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -614,6 +646,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" name = "lore-core" version = "0.62.35" dependencies = [ + "doxa-codegraph", "fancy-regex", "hmac", "http-body-util", @@ -1007,7 +1040,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -1016,6 +1049,7 @@ version = "1.0.151" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" dependencies = [ + "indexmap", "itoa", "memchr", "serde", @@ -1102,12 +1136,29 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" + [[package]] name = "subtle" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.6" @@ -1136,7 +1187,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -1169,7 +1220,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -1242,7 +1293,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] @@ -1319,6 +1370,36 @@ dependencies = [ "once_cell", ] +[[package]] +name = "tree-sitter" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87" +dependencies = [ + "cc", + "regex", + "regex-syntax", + "serde_json", + "streaming-iterator", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-language" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a" + +[[package]] +name = "tree-sitter-python" +version = "0.23.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d065aaa27f3aaceaf60c1f0e0ac09e1cb9eb8ed28e7bcdaa52129cffc7f4b04" +dependencies = [ + "cc", + "tree-sitter-language", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -1442,7 +1523,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 3.0.6", "wasm-bindgen-shared", ] @@ -1597,7 +1678,7 @@ checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", "synstructure", ] @@ -1618,7 +1699,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", "synstructure", ] @@ -1658,7 +1739,7 @@ checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.6", ] [[package]] diff --git a/README.md b/README.md index 2d31fc1..e08bb33 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,8 @@ are hard-capped; curated proposals wait for review. Derived beliefs retain their evidence and appear on request or through explicitly enabled context. -Gemini sessions launched through Google Antigravity in DOXA share the same -memory and local session index. The standalone Antigravity companion records -tool evidence. [Antigravity setup](#google-antigravity) +Gemini sessions in Google Antigravity can use the same memory and local session +index through standalone hooks or DOXA. [Antigravity setup](#google-antigravity) > [!WARNING] > **Beta.** Commands, caps, and configuration may change between releases. @@ -44,6 +43,8 @@ matches for review. [Release notes](https://github.com/docwilde/LORE/releases/ta demand, or enable experimental, bounded graph context. - **Session search.** Local FTS5 index of Claude Code, DOXA, and Codex transcripts. - **File maps.** A short `path — purpose` guide to important project files. +- **AST codegraph.** Inspect Rust and Python definitions, imports, call sites, + and module layout in the current Git worktree. [Codegraph commands](docs/manual.md#ast-codegraph) - **Bounded pending review.** [Page through large queues](docs/pending-pages.md) while preserving human review of each complete, exact proposal. - **Reviewed cleanup.** [Preview diagnostic retention and select orphaned @@ -117,16 +118,22 @@ directory’s LORE memory on the first turn and indexes the scrubbed transcript on session shutdown. Set `DOXA_LORE=0` to disable both for a session. [DOXA Antigravity setup](https://github.com/docwilde/doxa/blob/main/docs/antigravity.md) -**Tool evidence in the standalone Antigravity CLI.** The `lore-tool-evidence` -companion records reported tool successes and failures in the local LORE store. -Install it from this checkout and keep `lore-rs` on `PATH`. +**Standalone Antigravity.** The `lore-tool-evidence` plugin loads shared +memory at conversation start, indexes completed chat steps when the agent +is idle, and records tool outcomes. Install it from this checkout and +keep `lore-rs` on `PATH`. ```sh ./task install agy plugin install "$PWD/antigravity" ``` -See [tool evidence](docs/tool-evidence.md) for storage and linking details. +The hooks use a single workspace to scope memory and indexing. Start a new +conversation to load the latest snapshot. Antigravity may retain the startup +context in its own history. The indexing hook stores scrubbed user and assistant +text locally. Use `LORE_DISABLE_INJECT=1` or `LORE_DISABLE_INDEX=1` +to turn off either hook. [Tool evidence](docs/tool-evidence.md) + ### Codex LORE supports Codex through the portable [`plugin.json`](plugin.json) and diff --git a/antigravity/hooks.json b/antigravity/hooks.json index 6334fa7..3352230 100644 --- a/antigravity/hooks.json +++ b/antigravity/hooks.json @@ -1,4 +1,20 @@ { + "lore-memory": { + "SessionStart": [ + { + "type": "command", + "command": "lore-rs hook --engine antigravity --event session-start", + "timeout": 10 + } + ], + "Stop": [ + { + "type": "command", + "command": "lore-rs hook --engine antigravity --event stop", + "timeout": 15 + } + ] + }, "lore-tool-evidence": { "enabled": true, "PostToolUse": [ diff --git a/antigravity/plugin.json b/antigravity/plugin.json index d458e9d..a02ad1e 100644 --- a/antigravity/plugin.json +++ b/antigravity/plugin.json @@ -2,5 +2,5 @@ "$schema": "https://antigravity.google/schemas/v1/plugin.json", "name": "lore-tool-evidence", "version": "0.62.35", - "description": "Record reported tool outcomes in the local LORE evidence store." + "description": "Load shared LORE memory at startup and index conversations and tool evidence locally." } diff --git a/docs/manual.md b/docs/manual.md index c084044..2867935 100644 --- a/docs/manual.md +++ b/docs/manual.md @@ -53,6 +53,25 @@ current project; they do not include proposals for unrelated projects. A file-map, skill, or belief proposal with a project identity is reviewed only from that project. +## AST codegraph + +`lore codegraph` queries the current Git worktree through the same bounded +Rust and Python AST engine used by DOXA. The engine is built into `lore-rs`. + +```sh +lore codegraph file src/lib.rs +lore codegraph symbol parse_config +lore codegraph imports tools/importer.py +lore codegraph calls src/lib.rs +lore codegraph modules src/lib.rs --cwd /path/to/worktree +``` + +The result includes source hashes, line locations, scan coverage, and omitted +counts. Imports are declarations. Call and module candidates describe syntax +or worktree layout. Compiler bindings and runtime import resolution stay +unknown. Queries read source without executing it and the index stays in +memory for the query. [DOXA AST engine notes](https://github.com/docwilde/doxa/blob/v2.0.0-beta.90/docs/plans/code-graph.md) + ## Six stores | Store | Location | Cap | Gate | diff --git a/docs/tool-evidence.md b/docs/tool-evidence.md index 1a70eb6..8fcda6c 100644 --- a/docs/tool-evidence.md +++ b/docs/tool-evidence.md @@ -11,7 +11,7 @@ Tool recording is on by default. Each observation records the provider, project, | 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. +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 plugin includes memory and indexing hooks for standalone conversations. DOXA handles LORE integration for its own Antigravity sessions. [Antigravity setup](../README.md#google-antigravity) 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. diff --git a/rust/lore-core/Cargo.toml b/rust/lore-core/Cargo.toml index 0e194f6..63a1c16 100644 --- a/rust/lore-core/Cargo.toml +++ b/rust/lore-core/Cargo.toml @@ -8,6 +8,7 @@ repository = "https://github.com/docwilde/LORE" publish = false [dependencies] +doxa-codegraph = { git = "https://github.com/docwilde/doxa", rev = "fa763acc8e738f461cd2f15ea8adfd8d58020328" } fancy-regex = "0.19.2" hmac = "0.12" libc = "0.2" diff --git a/rust/lore-core/src/context.rs b/rust/lore-core/src/context.rs index b0c0f74..883ea4b 100644 --- a/rust/lore-core/src/context.rs +++ b/rust/lore-core/src/context.rs @@ -134,6 +134,9 @@ fn rendered_memory(cfg: &Config, scope: Scope, key: &str, entries: &[String]) -> .to_owned() } fn freshness_rule(policy: RefreshPolicy, engine: &str) -> String { + if engine == "antigravity" { + return "- In Antigravity, LORE loads this snapshot at the start of a new conversation. Read current files during the conversation with lore-rs memory show.".into(); + } if engine == "codex" { return "- In Codex, this snapshot is injected at startup, resume, clear, and compaction. Writes land in the files immediately; read them during this session with lore-rs memory show.".into(); } diff --git a/rust/lore-core/src/index.rs b/rust/lore-core/src/index.rs index c1c8bb5..b146574 100644 --- a/rust/lore-core/src/index.rs +++ b/rust/lore-core/src/index.rs @@ -330,6 +330,110 @@ pub fn parse_transcript_fd(file: &File, codex: bool) -> Result<(Metadata, Vec Result<()> { + let Some(file) = crate::files::open_regular_if_exists(path, MAX_FILE as usize)? else { + return Ok(()); + }; + let version = |st: &fs::Metadata| { + ( + st.dev(), + st.ino(), + st.len(), + st.mtime(), + st.mtime_nsec(), + st.ctime(), + st.ctime_nsec(), + ) + }; + let st = descriptor(&file)?; + let mut rows = Vec::new(); + lines(&file, st.len(), |_, raw, _| { + if raw.trim().is_empty() { + return Ok(()); + } + let row: Value = serde_json::from_str(raw).map_err(|_| Error::Changed)?; + if row["status"] != "DONE" { + return Ok(()); + } + let Some(text) = row["content"].as_str() else { + return Ok(()); + }; + let (role, text) = match (row["type"].as_str(), row["source"].as_str()) { + (Some("USER_INPUT"), Some("USER_EXPLICIT")) => { + // The CLI appends clock and settings annotations to wrapped input. + let request = text.strip_prefix("\n") + .and_then(|body| body.rsplit_once("\n")) + .map_or(text, |(request, _)| request); + ("user", request) + } + (Some("PLANNER_RESPONSE"), Some("MODEL")) => ("assistant", text), + _ => return Ok(()), + }; + let text = text.trim(); + if text.is_empty() { + return Ok(()); + } + if rows.len() == MAX_MESSAGES { + return Err(Error::TooLarge); + } + rows.push(Message { + ts: scrub::scrub(&string(&row["created_at"], 128).unwrap_or_default())?, + role: role.into(), + content: clean_text(text)?, + }); + Ok(()) + })?; + let (Some(first), Some(last)) = (rows.first(), rows.last()) else { + return Ok(()); + }; + let cwd_text = scrub::scrub(cwd.to_str().ok_or(Error::InvalidRequest)?)?; + let project = config::project_slug(cwd); + let mut conn = store::connect(cfg)?; + let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; + // Recheck under the index lock so a late hook cannot replace newer rows + // with a snapshot captured before another Stop notification. + let current = crate::files::open_regular(path, MAX_FILE as usize)?; + if version(&st) != version(¤t.metadata()?) { + return Err(Error::Changed); + } + let existing = tx + .query_row( + "SELECT engine,project,cwd FROM sessions WHERE session_id=?", + [sid], + |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, Option>(1)?, + row.get::<_, Option>(2)?, + )) + }, + ) + .optional()?; + if existing + .as_ref() + .is_some_and(|(engine, saved_project, saved_cwd)| { + engine != "antigravity" + || saved_project.as_deref() != Some(project.as_str()) + || saved_cwd.as_deref() != Some(cwd_text.as_str()) + }) + { + return Err(Error::Changed); + } + tx.execute("DELETE FROM msg WHERE session_id=?", [sid])?; + write_rows(&tx, sid, &project, &rows)?; + tx.execute( + "INSERT INTO sessions(session_id,project,cwd,first_ts,last_ts,messages,engine) + VALUES(?,?,?,?,?,?,'antigravity') ON CONFLICT(session_id) DO UPDATE + SET first_ts=excluded.first_ts,last_ts=excluded.last_ts,messages=excluded.messages", + params![sid, project, cwd_text, first.ts, last.ts, crate::beliefs::sql_integer(rows.len())?], + )?; + tx.commit()?; + Ok(()) +} + fn msgs_payload(conn: &Connection, sid: &str) -> Result { // Read the current persisted snapshot inside the caller's mutation lock. let mut stmt = conn diff --git a/rust/lore-core/src/scrub.rs b/rust/lore-core/src/scrub.rs index 0576ff5..1fbdaf0 100644 --- a/rust/lore-core/src/scrub.rs +++ b/rust/lore-core/src/scrub.rs @@ -186,8 +186,16 @@ pub fn scrub(text: &str) -> Result { Ok(text) } pub fn scrub_json(value: &serde_json::Value) -> Result { + scrub_json_with_digests(value, &[]) +} + +/// Preserve named digests in JSON serialized from typed local output. +pub(crate) fn scrub_json_with_digests( + value: &serde_json::Value, + digest_fields: &[&str], +) -> Result { use serde_json::Value; - fn walk(value: &Value, depth: usize) -> Result { + fn walk(value: &Value, depth: usize, digest_fields: &[&str]) -> Result { if depth > 32 { return Err(Error::TooLarge); } @@ -195,12 +203,23 @@ pub fn scrub_json(value: &serde_json::Value) -> Result { Value::String(s) => Value::String(scrub(s)?), Value::Array(a) => Value::Array( a.iter() - .map(|v| walk(v, depth + 1)) + .map(|v| walk(v, depth + 1, digest_fields)) .collect::>()?, ), Value::Object(o) => Value::Object( o.iter() - .map(|(k, v)| Ok((k.clone(), walk(v, depth + 1)?))) + .map(|(k, v)| { + let clean = if digest_fields.contains(&k.as_str()) + && v.as_str().is_some_and(|s| { + s.len() == 64 && s.bytes().all(|byte| byte.is_ascii_hexdigit()) + }) + { + v.clone() + } else { + walk(v, depth + 1, digest_fields)? + }; + Ok((k.clone(), clean)) + }) .collect::>()?, ), _ => value.clone(), @@ -213,7 +232,7 @@ pub fn scrub_json(value: &serde_json::Value) -> Result { { return Err(Error::TooLarge); } - walk(value, 0) + walk(value, 0, digest_fields) } #[cfg(test)] mod tests { diff --git a/rust/lore-core/src/standalone.rs b/rust/lore-core/src/standalone.rs index 244cd3a..6935c80 100644 --- a/rust/lore-core/src/standalone.rs +++ b/rust/lore-core/src/standalone.rs @@ -21,7 +21,9 @@ Memory: memory show|entries|usage|review|add|replace|remove|move Beliefs: belief list|search|show|review|add|retract|edges|dedup-report evidence consult ask outcome stats audit crosscheck dream Graph: graph stats|neighbours|path|communities|components|degree|context|html|backfill|derive|edge -Codegraph: codegraph store --cwd WORKTREE --input FILE --expected-sha256 HASH --expected-revision N +Codegraph: codegraph file|imports|calls|modules PATH [--cwd WORKTREE] + codegraph symbol NAME [--cwd WORKTREE] + codegraph store --cwd WORKTREE --input FILE --expected-sha256 HASH --expected-revision N codegraph cleanup-plan|cleanup-apply --json REVIEWED_PLAN Sessions: search session index history recent|prefix|metadata Review: review backfill pending list|page|show approve reject @@ -406,6 +408,31 @@ pub fn run(args: &[String]) -> Result<()> { } ("trace", "retention-plan") => crate::retention::plan(&cfg, &req)?, ("trace", "retention-apply") => crate::retention::apply(&cfg, &req, &auth)?, + ("codegraph", kind @ ("file" | "symbol" | "imports" | "calls" | "modules")) => { + let [value] = p.as_slice() else { + return Err(Error::InvalidRequest); + }; + use doxa_codegraph::Query; + let query = match kind { + "file" => Query::File(value.clone()), + "symbol" => Query::Symbol(value.clone()), + "imports" => Query::Imports(value.clone()), + "calls" => Query::Calls(value.clone()), + _ => Query::Modules(value.clone()), + }; + let answer = doxa_codegraph::query(crate::gate::cwd(&req)?, query).map_err(|message| { + if let Ok(message) = crate::scrub::scrub(&message) { + eprintln!("lore-rs: codegraph: {message}"); + } + Error::Unavailable + })?; + let value = serde_json::to_value(answer).map_err(|_| Error::Unavailable)?; + crate::scrub::scrub_json_with_digests(&value, &[ + "sha256", "source_sha256", "requested_source_sha256", "scan_input_sha256", + "python_scan_input_sha256", "target_sha256", "conditional_candidate_sha256", + "structural_candidate_sha256", + ])? + } ("codegraph", "cleanup-plan") => crate::codegraph_snapshot::cleanup_plan(&cfg, &req)?, ("codegraph", "cleanup-apply") => crate::codegraph_snapshot::cleanup_apply(&cfg, &req, &auth)?, ("trace", "capture") => crate::diagnostics::capture(&cfg, &req)?, @@ -1250,15 +1277,13 @@ pub fn hook(cfg: &Config, args: &[String]) -> Result<()> { } let engine = options["engine"] .as_str() - .filter(|s| matches!(*s, "claude" | "codex")) + .filter(|s| matches!(*s, "claude" | "codex" | "antigravity")) .ok_or(Error::InvalidRequest)?; let event = options["event"] .as_str() - .filter(|s| { - matches!( - *s, - "session-start" | "prompt" | "pre-compact" | "session-end" - ) + .filter(|s| match engine { + "antigravity" => matches!(*s, "session-start" | "stop"), + _ => matches!(*s, "session-start" | "prompt" | "pre-compact" | "session-end"), }) .ok_or(Error::InvalidRequest)?; let mut raw = Vec::new(); @@ -1273,6 +1298,21 @@ pub fn hook(cfg: &Config, args: &[String]) -> Result<()> { if !input.is_object() { return Err(Error::InvalidRequest); } + if engine == "antigravity" { + let noop = if event == "stop" { + json!({"decision":"stop"}) + } else { + json!({}) + }; + return output(match crate::standalone_hooks::antigravity(cfg, event, &input) { + Ok(Some(response)) => response, + Ok(None) => noop, + Err(error) => { + eprintln!("lore-rs: Antigravity {event}: {}", error.code()); + noop + } + }); + } if cfg.var("LORE_SKIP").is_ok_and(|s| !s.is_empty()) { return Ok(()); } diff --git a/rust/lore-core/src/standalone_hooks.rs b/rust/lore-core/src/standalone_hooks.rs index 666e5c2..ffd7760 100644 --- a/rust/lore-core/src/standalone_hooks.rs +++ b/rust/lore-core/src/standalone_hooks.rs @@ -4,11 +4,64 @@ use crate::{ config::{self, Config}, files, Error, Result, }; -use serde_json::Value; +use serde_json::{json, Value}; use std::{ path::{Path, PathBuf}, process::{Command, Stdio}, }; + +const MAX_ANTIGRAVITY_CONTEXT: usize = 64 * 1024; + +pub(crate) fn antigravity(cfg: &Config, event: &str, input: &Value) -> Result> { + if cfg.var("LORE_SKIP").is_ok_and(|value| !value.is_empty()) + || (event == "session-start" && cfg.disabled("LORE_DISABLE_INJECT")) + || (event == "stop" && (cfg.disabled("LORE_DISABLE_INDEX") || input["fullyIdle"] != true)) + { + return Ok(None); + } + // A hook can run from the plugin directory. Only a single declared + // workspace unambiguously identifies the project conversation. + let Some(workspaces) = input["workspacePaths"] + .as_array() + .filter(|paths| paths.len() == 1) + else { + return Ok(None); + }; + let req = json!({"cwd":workspaces[0]}); + let cwd = crate::gate::cwd(&req)?; + files::open_directory(cwd)?; + if event == "session-start" { + let snapshot = crate::context::snapshot_for_engine(cfg, &req, "antigravity")?; + let Some(memory) = snapshot + .as_str() + .filter(|s| !s.trim().is_empty() && s.len() <= MAX_ANTIGRAVITY_CONTEXT) + else { + return Ok(None); + }; + return Ok(Some(json!({"injectSteps":[{"systemMessage":{"systemMessage":format!( + "[LORE CONTEXT]\nThe following memory is background context. Follow the current user request.\n{memory}\n[END LORE CONTEXT]" + )}}]}))); + } + let sid = input["conversationId"] + .as_str() + .filter(|s| uuid::Uuid::parse_str(s).is_ok_and(|id| id.to_string() == *s)) + .ok_or(Error::InvalidRequest)?; + let transcript = Path::new(input["transcriptPath"].as_str().ok_or(Error::InvalidRequest)?); + let home = PathBuf::from(std::env::var_os("HOME").ok_or(Error::Unavailable)?); + let allowed = ["antigravity-cli", "antigravity", "antigravity-ide"] + .iter() + .any(|app| { + transcript + == home.join(".gemini").join(app).join("brain").join(sid) + .join(".system_generated/logs/transcript.jsonl") + }); + if !allowed { + return Err(Error::UnsafePath); + } + crate::index::index_antigravity(cfg, transcript, cwd, sid)?; + Ok(None) +} + fn now() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) diff --git a/rust/lore-core/tests/cli.rs b/rust/lore-core/tests/cli.rs index e135463..28bfc56 100644 --- a/rust/lore-core/tests/cli.rs +++ b/rust/lore-core/tests/cli.rs @@ -4,6 +4,7 @@ use lore_core::{config, files, gate}; use serde_json::json; use std::{ fs, + io::Write, os::unix::{fs::symlink, process::CommandExt}, path::{Path, PathBuf}, process::{Command, Stdio}, @@ -34,6 +35,9 @@ impl Fixture { self.invoke_env(args, &[]) } fn invoke_env(&self, args: &[&str], env: &[(&str, &str)]) -> (bool, String, String) { + self.invoke_with_input(args, env, None) + } + fn invoke_with_input(&self, args: &[&str], env: &[(&str, &str)], input: Option<&str>) -> (bool, String, String) { let out = self.home.join("stdout"); let err = self.home.join("stderr"); let mut child = Command::new(env!("CARGO_BIN_EXE_lore-rs")) @@ -48,11 +52,14 @@ impl Fixture { .envs(env.iter().copied()) .current_dir(&self.cwd) .process_group(0) - .stdin(Stdio::null()) + .stdin(if input.is_some() { Stdio::piped() } else { Stdio::null() }) .stdout(Stdio::from(fs::File::create(&out).unwrap())) .stderr(Stdio::from(fs::File::create(&err).unwrap())) .spawn() .unwrap(); + if let Some(input) = input { + child.stdin.take().unwrap().write_all(input.as_bytes()).unwrap(); + } let deadline = Instant::now() + Duration::from_secs(3); let ready = loop { let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() }; @@ -99,6 +106,99 @@ impl Fixture { .join(format!("{}.md", config::project_slug(&self.cwd))) } } + +#[test] +fn antigravity_start_injects_only_the_declared_workspace() { + let fixture = Fixture::new(); + let workspace = fixture.home.join("workspace"); + fs::create_dir(&workspace).unwrap(); + fixture.write(&fixture.project(), "- wrong workspace fact\n"); + fixture.write(&fixture.root.join("projects").join(config::project_slug(&workspace)).join("MEMORY.md"), + "- selected workspace fact\n"); + let args = ["hook", "--engine", "antigravity", "--event", "session-start"]; + let input = json!({"workspacePaths":[workspace]}).to_string(); + let (ok, out, error) = fixture.invoke_with_input(&args, &[], Some(&input)); + assert!(ok && error.is_empty(), "{error}"); + let response: serde_json::Value = serde_json::from_str(&out).unwrap(); + let text = response["injectSteps"][0]["systemMessage"]["systemMessage"].as_str().unwrap(); + assert!(text.contains("selected workspace fact")); + assert!(!text.contains("wrong workspace fact")); + let ambiguous = json!({"workspacePaths":[workspace, fixture.cwd]}).to_string(); + for (input, env) in [(&ambiguous, &[][..]), (&input, &[("LORE_DISABLE_INJECT", "1")][..])] { + let (ok, out, error) = fixture.invoke_with_input(&args, env, Some(input)); + assert!(ok && error.is_empty(), "{error}"); + assert_eq!(out.trim(), "{}"); + } +} + +#[test] +fn antigravity_stop_indexes_owned_chat_steps_and_is_safe_to_repeat() { + let fixture = Fixture::new(); + let sid = "5b200830-3bc3-4e5b-aa56-4e0649feaddb"; + let transcript = fixture.home.join(".gemini/antigravity-cli/brain").join(sid) + .join(".system_generated/logs/transcript.jsonl"); + fixture.write(&transcript, concat!( + "{\"type\":\"SYSTEM_MESSAGE\",\"source\":\"SYSTEM\",\"status\":\"DONE\",\"content\":\"injected memory\"}\n", + "{\"type\":\"USER_INPUT\",\"source\":\"USER_EXPLICIT\",\"status\":\"DONE\",\"created_at\":\"2026-11-25T00:00:00Z\",\"content\":\"\\nlorehookneedle question\\n\\nprivate clock metadata\"}\n", + "{\"type\":\"GENERIC\",\"source\":\"MODEL\",\"status\":\"DONE\",\"content\":\"tool output\"}\n", + "{\"type\":\"PLANNER_RESPONSE\",\"source\":\"MODEL\",\"status\":\"DONE\",\"created_at\":\"2026-11-25T00:00:01Z\",\"content\":\"answer sk-abcdefghijklmnopqrstuvwxyz123456\",\"thinking\":\"private reasoning\"}\n", + )); + let args = ["hook", "--engine", "antigravity", "--event", "stop"]; + let event = json!({"workspacePaths":[fixture.cwd],"conversationId":sid, + "transcriptPath":transcript,"fullyIdle":true}); + let mut busy = event.clone(); + busy["fullyIdle"] = json!(false); + let (ok, _, _) = fixture.invoke_with_input(&args, &[], Some(&busy.to_string())); + assert!(ok && !fixture.root.exists()); + for _ in 0..2 { + let (ok, out, error) = fixture.invoke_with_input(&args, &[], Some(&event.to_string())); + assert!(ok && error.is_empty(), "{error}"); + assert_eq!(serde_json::from_str::(&out).unwrap(), json!({"decision":"stop"})); + } + let (ok, out, error) = fixture.invoke(&["session", sid]); + assert!(ok, "{error}"); + let session: serde_json::Value = serde_json::from_str(&out).unwrap(); + assert_eq!(session["session"][0]["engine"], "antigravity"); + assert_eq!(session["rows"].as_array().unwrap().len(), 2); + assert_eq!(session["rows"][0]["content"], "lorehookneedle question"); + assert!(!out.contains("injected memory") && !out.contains("tool output") && !out.contains("private reasoning")); + assert!(!out.contains("sk-abcdefghijklmnopqrstuvwxyz123456")); + let (ok, out, error) = fixture.invoke(&["search", "lorehookneedle"]); + assert!(ok && out.contains(sid), "{error}"); + + let other_file = fixture.home.join("other-transcript.jsonl"); + fs::rename(&transcript, &other_file).unwrap(); + symlink(&other_file, &transcript).unwrap(); + let (ok, out, error) = fixture.invoke_with_input(&args, &[], Some(&event.to_string())); + assert!(ok && out.contains("stop") && error.contains("unsafe_path"), "{error}"); +} + +#[test] +fn standalone_codegraph_queries_rust_and_python_without_a_memory_store() { + let fixture = Fixture::new(); + assert!(Command::new("git").args(["init", "-q"]) + .current_dir(&fixture.cwd).status().unwrap().success()); + let rust = "use std::fmt;\npub fn root() { helper(); }\nfn helper() {}\nmod child;\n"; + fs::write(fixture.cwd.join("lib.rs"), rust).unwrap(); + fs::write(fixture.cwd.join("child.rs"), "pub fn child() {}\n").unwrap(); + fs::write(fixture.cwd.join("app.py"), "from pathlib import Path\ndef action():\n return Path('.')\n").unwrap(); + let query = |kind: &str, input: &str| -> serde_json::Value { + let (ok, reply, error) = fixture.invoke_env( + &["codegraph", kind, input], + &[("PATH", "/usr/bin:/bin")], + ); + assert!(ok, "{kind}: {error}"); + serde_json::from_str(&reply).unwrap() + }; + assert_eq!(query("file", "lib.rs")["requested_source_sha256"], lore_core::digest(rust.as_bytes())); + assert_eq!(query("symbol", "action")["rows"][0]["file"], "app.py"); + assert!(query("imports", "app.py")["rows"].as_array().is_some_and(|rows| !rows.is_empty())); + assert_eq!(query("calls", "lib.rs")["edges"][0]["binding"], "candidate_only"); + assert_eq!(query("modules", "lib.rs")["module_edges"][0]["target"], "child.rs"); + let (ok, _, _) = fixture.invoke_env(&["codegraph", "file", "../outside.rs"], &[("PATH", "/usr/bin:/bin")]); + assert!(!ok); + assert!(!fixture.root.exists()); +} fn tree(root: &Path) -> Vec<(PathBuf, Vec)> { let mut rows = Vec::new(); if let Ok(entries) = fs::read_dir(root) { From 045cff76a16f35e7d4ba462eb9e371a6b7586cb0 Mon Sep 17 00:00:00 2001 From: "Dr. Fabian Wilde" Date: Thu, 26 Nov 2026 14:35:40 +0100 Subject: [PATCH 2/2] release(lore): prepare 0.62.36 --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- CHANGELOG.md | 12 ++++++++++++ Cargo.lock | 2 +- README.md | 5 ++--- antigravity/plugin.json | 2 +- plugin.json | 2 +- rust/lore-core/Cargo.toml | 2 +- 8 files changed, 20 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index a52c04e..32be00e 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.35" + "version": "0.62.36" } ] } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 0ad2bdb..d234bdc 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.35", + "version": "0.62.36", "author": { "name": "Fabian Wilde", "email": "docwilde@proton.me" diff --git a/CHANGELOG.md b/CHANGELOG.md index 6806a3e..1225c9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 0.62.36 — 2026-11-26 + +**Standalone Antigravity** + +- Load workspace memory through the native `SessionStart` hook. +- Index completed transcript messages locally through the native `Stop` hook. + +**AST codegraph** + +- Add `lore codegraph` queries for Rust and Python definitions, imports, + calls, symbols, and modules in a Git worktree. + ## 0.62.35 — 2026-11-25 - Exclude historical heuristic audit outcomes from belief calibration, graph ranking, and the STEER threshold. Preserve signed ledger history. diff --git a/Cargo.lock b/Cargo.lock index 65b5482..c5d7207 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -644,7 +644,7 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "lore-core" -version = "0.62.35" +version = "0.62.36" dependencies = [ "doxa-codegraph", "fancy-regex", diff --git a/README.md b/README.md index e08bb33..2e16bfb 100644 --- a/README.md +++ b/README.md @@ -33,9 +33,8 @@ and relations between beliefs do not turn them into approved facts. ## What you get -LORE 0.62.35 excludes historical heuristic audit outcomes from belief -calibration and the STEER threshold. `lore audit` reports path and Git token -matches for review. [Release notes](https://github.com/docwilde/LORE/releases/tag/v0.62.35) +LORE 0.62.36 adds standalone Antigravity memory hooks and AST codegraph queries +for Rust and Python. [Release notes](https://github.com/docwilde/LORE/releases/tag/v0.62.36) - **Claude Code, Codex, and DOXA memory.** Share one native store for capped user and project facts across engines; host facts stay local. diff --git a/antigravity/plugin.json b/antigravity/plugin.json index a02ad1e..51ed6b3 100644 --- a/antigravity/plugin.json +++ b/antigravity/plugin.json @@ -1,6 +1,6 @@ { "$schema": "https://antigravity.google/schemas/v1/plugin.json", "name": "lore-tool-evidence", - "version": "0.62.35", + "version": "0.62.36", "description": "Load shared LORE memory at startup and index conversations and tool evidence locally." } diff --git a/plugin.json b/plugin.json index b52c04e..1239937 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.35", + "version": "0.62.36", "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 63a1c16..360426b 100644 --- a/rust/lore-core/Cargo.toml +++ b/rust/lore-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lore-core" -version = "0.62.35" +version = "0.62.36" edition = "2021" license = "AGPL-3.0-only" description = "Native LORE memory, beliefs, review and session index"