From 0d73f6fd9df265b67484e77b9029b1f78ce1c5e4 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 4 Oct 2026 16:00:00 -0500 Subject: [PATCH] agent-archive: initial collectors (claude, codex, opencode, gemini, muse) Co-Authored-By: Claude Fable 5.1 --- .crumb | 20 ++ .gitignore | 1 + Cargo.lock | 548 ++++++++++++++++++++++++++++++++++++ Cargo.toml | 16 ++ README.md | 70 +++++ src/collectors.rs | 343 ++++++++++++++++++++++ src/core.rs | 255 +++++++++++++++++ src/main.rs | 302 ++++++++++++++++++++ src/pb.rs | 86 ++++++ tests/fixtures/claude.jsonl | 4 + tests/fixtures/codex.jsonl | 7 + tests/fixtures/muse.jsonl | 4 + 12 files changed, 1656 insertions(+) create mode 100644 .crumb create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 README.md create mode 100644 src/collectors.rs create mode 100644 src/core.rs create mode 100644 src/main.rs create mode 100644 src/pb.rs create mode 100644 tests/fixtures/claude.jsonl create mode 100644 tests/fixtures/codex.jsonl create mode 100644 tests/fixtures/muse.jsonl diff --git a/.crumb b/.crumb new file mode 100644 index 0000000..171d587 --- /dev/null +++ b/.crumb @@ -0,0 +1,20 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-04T21:00:00Z", + "compiler": "crumb-compile/1", + "digest": "sha256:b418596a32d581eec665bc82128d24920f3efc74048d7749774c1e68f3b3db6b", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 1, + "generated_at_commit": "4ad39c0151ad796dfd6e794859edc3860ed8f355", + "source_tree": "sha256:65d67e74597617173d13640bd7dd588567acf0b85da985f90288c8fd41860f20" + } + }, + "layer": "tooling", + "name": "agent-archive", + "purpose": "central archive of all AI agent chats on the Spark", + "schema_version": "1.0.0" +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..ab9f946 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,548 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "agent-archive" +version = "0.1.0" +dependencies = [ + "chrono", + "regex", + "rusqlite", + "serde_json", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cc" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..eb9ae24 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "agent-archive" +version = "0.1.0" +edition = "2021" +license = "AGPL-3.0-or-later" +description = "Central archive of every AI agent chat on the Spark" + +[dependencies] +serde_json = "1" +rusqlite = { version = "0.32", features = ["bundled"] } +chrono = { version = "0.4", default-features = false, features = ["std", "clock"] } +regex = "1" + +[profile.release] +opt-level = 3 +strip = true diff --git a/README.md b/README.md new file mode 100644 index 0000000..95d3fbb --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +# agent-archive + +One central, long-term archive of every AI agent chat on the DGX Spark: Claude Code, Codex, OpenCode, +Gemini/Antigravity (Spark and MacBook) and Muse. Plain JSONL files, one common record per message, +plus a verbatim mirror of the original source files. Single Rust binary, no Python, no network except a +read-only `ssh`/`scp` pull from the MacBook. + +## Layout + +Archive root: `~/archive/agent-chats/` (override with `AGENT_ARCHIVE_ROOT`). + +| Path | What | +|---|---| +| `records//.jsonl` | common records, append-only, date = message timestamp (UTC) | +| `raw///` | verbatim copies of the source files (JSONL appended byte for byte as they grow; sqlite files copied when they change) | +| `latest/.txt`, `latest/.jsonl` | rolling window, last 20000 records, rewritten atomically (temp file + rename). `.txt` lines look like `[ts session8 role] text` with newlines shown as `\n` | +| `state/.json` | per-source cursors (byte offsets, row cursors, file signatures) | + +State loss only causes re-reads: records are de-duplicated on `(agent, host, session, role, src.path, src.pos)` +and the raw mirror never writes bytes it already has. + +## Record schema + +```json +{"ts":"2026-10-04T20:00:00.000Z","agent":"claude|codex|opencode|gemini|muse","host":"spark|macbook", + "session":"","role":"user|assistant|system|tool","text":"...","model":null,"cwd":null, + "src":{"path":"...","pos":123}} +``` + +`src.pos` is the byte offset of the source line (JSONL sources), the step index (Gemini) or a stable hash of the +part id (OpenCode). Only conversational text is turned into records; tool calls and results stay in `raw/`. + +## Commands + +``` +agent-archive collect # loop every 10 s (run detached) +agent-archive once [--no-mac] # one pass, prints per-agent counts and duration +agent-archive status # per agent: last record, today/total, sources, preview +agent-archive query --agent claude --since 2026-10-04T00:00:00Z --grep 'regex' --limit 50 [--json] +agent-archive debug-pb FILE # dump a raw protobuf blob (for Gemini format work) +``` + +## Sources and parsers + +| Agent | Source | Status | +|---|---|---| +| claude | `~/.claude/projects/**/*.jsonl`, lines `type` user/assistant, text blocks only | verified on live data | +| codex | `~/.codex/sessions/**/*.jsonl`, `response_item` messages (`developer` becomes `system`) | verified on live data | +| opencode | `~/.local/share/opencode/opencode.db` (opened read-only), `text` parts; raw mirror is `raw/opencode/spark/opencode-rows.jsonl` (the rows, verbatim JSON) because the database is live | verified on live data | +| gemini | per-conversation sqlite `.db` in `~/.gemini/antigravity-{cli,ide}/conversations` (Spark) and, via `ssh macbook` + `scp`, `~/.gemini/antigravity{,-cli,-ide}/conversations` on the Mac into `raw/gemini/macbook/` | UNVERIFIED format: step blobs are protobuf with no schema available; field numbers (user text 19.3.1, reply 20.1, time 5.1) were inferred from sampling. Reply "thinking" text (20.3) is not turned into records. Mac WAL files are pulled but a `-shm` is not, so uncommitted Mac data may be missed | +| muse | `~/.local/share/muse/sessions/**/session.jsonl`; user text from `runtime.user_intent.accepted`, replies from `assistant_message_committed` | partly verified: the original design note named `turn.input.user` / `run.output.delta`, but those do not occur in the 81 sessions on disk, so the events above are used instead. Framed `retained_frame` lines are only kept in raw | + +The Mac pull is skipped (with a log line) if `ssh macbook` fails, and runs at most every 5 minutes. +`~/.gemini/antigravity-cli/history.jsonl` is command history only and is mirrored raw. + +## Adding a collector + +1. Add `parse_(line, path, pos, host) -> Vec` in `src/collectors.rs` (pure function). +2. For JSONL sources call `drive_jsonl(...)` from a `collect_` function; for databases keep a cursor with + `store.cursor/set_cursor` and call `store.emit(record, check_dup)`. +3. Register it in `pass()` in `src/main.rs`, add the name to `AGENTS` in `src/core.rs`. +4. Cut a small fixture from a real sample (no secrets) into `tests/fixtures/` and add a unit test. + +## Cortex rule + +Raw chat never goes into Cortex (house rule). Cortex gets only short digests plus a pointer to this archive, later. + +## License + +AGPL-3.0-or-later. diff --git a/src/collectors.rs b/src/collectors.rs new file mode 100644 index 0000000..2646d7c --- /dev/null +++ b/src/collectors.rs @@ -0,0 +1,343 @@ +//! One collector per agent. Parsers are pure functions (line -> records) so they can be unit tested on fixtures. +use crate::core::*; +use crate::pb; +use rusqlite::{Connection, OpenFlags}; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub struct Cfg { + pub home: PathBuf, + pub host: String, + pub mac: bool, +} + +fn rel(p: &Path, base: &Path) -> String { p.strip_prefix(base).unwrap_or(p).to_string_lossy().to_string() } + +/// Join text blocks of a Claude-style content value (string, or array of {type:text,text}). +fn blocks_text(c: &Value, kinds: &[&str]) -> String { + match c { + Value::String(s) => s.clone(), + Value::Array(a) => a.iter() + .filter(|b| b.get("type").or_else(|| b.get("kind")).and_then(|t| t.as_str()).map(|t| kinds.contains(&t)).unwrap_or(false)) + .filter_map(|b| b.get("text").and_then(|t| t.as_str())) + .collect::>().join("\n"), + _ => String::new(), + } +} + +// ---------------- generic JSONL driver ---------------- +fn drive_jsonl(store: &mut Store, agent: &str, host: &str, base: &Path, file: &Path, mut parse: F) -> std::io::Result<()> +where F: FnMut(&str, &str, u64, &mut Value) -> Vec { + let key = rel(file, base); + let cur = store.cursor(agent, &key).cloned(); + let (pos0, mut aux) = match &cur { + Some(Value::Object(o)) => (o.get("pos").and_then(|p| p.as_u64()).unwrap_or(0), cur.clone().unwrap()), + Some(v) => (v.as_u64().unwrap_or(0), json!({})), + None => (0, json!({})), + }; + if let Ok(m) = std::fs::metadata(file) { if m.len() == pos0 && cur.is_some() { return Ok(()); } } + let raw = store.root.join("raw").join(agent).join(host).join(&key); + let mut recs: Vec = Vec::new(); + let path_s = file.to_string_lossy().to_string(); + let (newpos, reset) = tail_lines(file, &raw, pos0, |line, pos| { recs.extend(parse(line, &path_s, pos, &mut aux)); })?; + let dup = cur.is_none() || reset; + for r in recs { store.emit(r, dup)?; } + let mut nv = if aux.is_object() { aux } else { json!({}) }; + nv["pos"] = json!(newpos); + store.set_cursor(agent, &key, nv); + Ok(()) +} + +// ---------------- claude ---------------- +pub fn parse_claude(line: &str, path: &str, pos: u64, host: &str) -> Vec { + let Ok(v) = serde_json::from_str::(line) else { return vec![] }; + let role = match v.get("type").and_then(|t| t.as_str()) { Some(r @ ("user" | "assistant")) => r, _ => return vec![] }; + let Some(ts) = v.get("timestamp").and_then(|t| t.as_str()).and_then(norm_ts) else { return vec![] }; + let text = blocks_text(v.pointer("/message/content").unwrap_or(&Value::Null), &["text"]); + if text.trim().is_empty() { return vec![]; } + let session = Path::new(path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + vec![Record { ts, agent: "claude".into(), host: host.into(), session, role: role.into(), text, + model: v.pointer("/message/model").and_then(|m| m.as_str()).map(String::from), + cwd: v.get("cwd").and_then(|m| m.as_str()).map(String::from), src_path: path.into(), src_pos: pos }] +} + +pub fn collect_claude(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { + let base = cfg.home.join(".claude/projects"); + let mut files = vec![]; walk(&base, "jsonl", &mut files); + for f in files { + let host = cfg.host.clone(); + drive_jsonl(store, "claude", &cfg.host, &base, &f, |l, p, pos, _| parse_claude(l, p, pos, &host))?; + } + Ok(()) +} + +// ---------------- codex ---------------- +fn codex_session(path: &str) -> String { + let stem = Path::new(path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + let b = stem.as_bytes(); + if b.len() >= 36 { + let t = &stem[stem.len() - 36..]; + if t.chars().enumerate().all(|(i, c)| if [8, 13, 18, 23].contains(&i) { c == '-' } else { c.is_ascii_hexdigit() }) { return t.to_string(); } + } + stem +} + +/// `aux` carries the per-file model/cwd learnt from session_meta / turn_context lines. +pub fn parse_codex(line: &str, path: &str, pos: u64, host: &str, aux: &mut Value) -> Vec { + let Ok(v) = serde_json::from_str::(line) else { return vec![] }; + match v.get("type").and_then(|t| t.as_str()) { + Some("turn_context") | Some("session_meta") => { + if let Some(m) = v.pointer("/payload/model").and_then(|x| x.as_str()) { aux["model"] = json!(m); } + if let Some(c) = v.pointer("/payload/cwd").and_then(|x| x.as_str()) { aux["cwd"] = json!(c); } + return vec![]; + } + Some("response_item") => {} + _ => return vec![], + } + let p = &v["payload"]; + if p.get("type").and_then(|t| t.as_str()) != Some("message") { return vec![]; } + let role = match p.get("role").and_then(|r| r.as_str()) { Some("user") => "user", Some("assistant") => "assistant", Some("developer") => "system", _ => return vec![] }; + let Some(ts) = v.get("timestamp").and_then(|t| t.as_str()).and_then(norm_ts) else { return vec![] }; + let text = blocks_text(&p["content"], &["input_text", "output_text"]); + if text.trim().is_empty() { return vec![]; } + vec![Record { ts, agent: "codex".into(), host: host.into(), session: codex_session(path), role: role.into(), text, + model: aux.get("model").and_then(|m| m.as_str()).map(String::from), + cwd: aux.get("cwd").and_then(|m| m.as_str()).map(String::from), src_path: path.into(), src_pos: pos }] +} + +pub fn collect_codex(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { + let base = cfg.home.join(".codex/sessions"); + let mut files = vec![]; walk(&base, "jsonl", &mut files); + for f in files { + let host = cfg.host.clone(); + drive_jsonl(store, "codex", &cfg.host, &base, &f, |l, p, pos, aux| parse_codex(l, p, pos, &host, aux))?; + } + Ok(()) +} + +// ---------------- muse ---------------- +pub fn parse_muse(line: &str, path: &str, pos: u64, host: &str) -> Vec { + let Ok(v) = serde_json::from_str::(line) else { return vec![] }; + let Some(pt) = v.get("payload_type").and_then(|t| t.as_str()) else { return vec![] }; // framed retained lines are skipped; raw keeps them + let Some(ts) = v.get("recorded_at").and_then(|t| t.as_i64()).and_then(|us| ts_from_ms(us / 1000)) else { return vec![] }; + let session = v.pointer("/stream/id").and_then(|s| s.as_str()).unwrap_or("").to_string(); + let mk = |role: &str, text: String| Record { ts: ts.clone(), agent: "muse".into(), host: host.into(), session: session.clone(), + role: role.into(), text, model: None, cwd: None, src_path: path.into(), src_pos: pos }; + if pt == "runtime.user_intent.accepted" { + let mut out = vec![]; + if let Some(ms) = v.pointer("/payload/model_messages").and_then(|m| m.as_array()) { + for m in ms { + let t = blocks_text(&m["content"], &["text"]); + if !t.trim().is_empty() { out.push(mk("user", t)); } + } + } + return out; + } + if pt == "runtime.session" && v.pointer("/payload/event/kind").and_then(|k| k.as_str()) == Some("assistant_message_committed") { + if let Some(t) = v.pointer("/payload/event/text").and_then(|t| t.as_str()) { + if !t.trim().is_empty() { return vec![mk("assistant", t.to_string())]; } + } + } + vec![] +} + +pub fn collect_muse(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { + let base = cfg.home.join(".local/share/muse/sessions"); + let mut files = vec![]; walk(&base, "jsonl", &mut files); + for f in files { + if f.file_name().map(|n| n != "session.jsonl").unwrap_or(true) { continue; } + let host = cfg.host.clone(); + drive_jsonl(store, "muse", &cfg.host, &base, &f, |l, p, pos, _| parse_muse(l, p, pos, &host))?; + } + Ok(()) +} + +// ---------------- opencode ---------------- +pub fn collect_opencode(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { + let dbp = cfg.home.join(".local/share/opencode/opencode.db"); + if !dbp.exists() { return Ok(()); } + let conn = match Connection::open_with_flags(&dbp, OpenFlags::SQLITE_OPEN_READ_ONLY) { Ok(c) => c, Err(_) => return Ok(()) }; + let _ = conn.busy_timeout(std::time::Duration::from_secs(5)); + let cur = store.cursor("opencode", "parts").and_then(|v| v.as_str()).unwrap_or("0|").to_string(); + let (ct, cid) = cur.split_once('|').map(|(a, b)| (a.parse::().unwrap_or(0), b.to_string())).unwrap_or((0, String::new())); + let fresh = store.cursor("opencode", "parts").is_none(); + let now_ms = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0); + let sql = "SELECT p.id, p.time_created, p.time_updated, p.data, m.data, s.id, s.directory, s.model \ + FROM part p JOIN message m ON m.id = p.message_id JOIN session s ON s.id = p.session_id \ + WHERE (p.time_created > ?1 OR (p.time_created = ?1 AND p.id > ?2)) AND json_extract(p.data,'$.type') = 'text' \ + ORDER BY p.time_created, p.id"; + let mut st = match conn.prepare(sql) { Ok(s) => s, Err(_) => return Ok(()) }; + let mut rows = match st.query(rusqlite::params![ct, cid]) { Ok(r) => r, Err(_) => return Ok(()) }; + let raw_path = store.root.join("raw/opencode").join(&cfg.host).join("opencode-rows.jsonl"); + std::fs::create_dir_all(raw_path.parent().unwrap())?; + let mut raw = std::fs::OpenOptions::new().create(true).append(true).open(&raw_path)?; + let mut last = (ct, cid.clone()); + while let Ok(Some(r)) = rows.next() { + let id: String = r.get(0).unwrap_or_default(); + let tc: i64 = r.get(1).unwrap_or(0); + let tu: i64 = r.get(2).unwrap_or(0); + if now_ms - tu < 30_000 { break; } // still streaming; take it on a later pass + let pdata: String = r.get(3).unwrap_or_default(); + let mdata: String = r.get(4).unwrap_or_default(); + let sid: String = r.get(5).unwrap_or_default(); + let dir: Option = r.get(6).ok(); + let smodel: Option = r.get(7).ok().flatten(); + let (pv, mv): (Value, Value) = (serde_json::from_str(&pdata).unwrap_or(Value::Null), serde_json::from_str(&mdata).unwrap_or(Value::Null)); + use std::io::Write; + let _ = writeln!(raw, "{}", json!({"part_id":id,"session_id":sid,"time_created":tc,"time_updated":tu,"part":pv,"message":mv})); + last = (tc, id.clone()); + let role = match mv.get("role").and_then(|x| x.as_str()) { Some(r @ ("user" | "assistant")) => r, _ => continue }; + let text = pv.get("text").and_then(|t| t.as_str()).unwrap_or(""); + if text.trim().is_empty() { continue; } + let Some(ts) = ts_from_ms(tc) else { continue }; + let model = mv.get("modelID").and_then(|x| x.as_str()).or_else(|| mv.pointer("/model/modelID").and_then(|x| x.as_str())).map(String::from).or(smodel); + let rec = Record { ts, agent: "opencode".into(), host: cfg.host.clone(), session: sid, role: role.into(), text: text.to_string(), + model, cwd: dir, src_path: "opencode.db#part".into(), src_pos: fnv(&id) }; + store.emit(rec, fresh)?; + } + drop(rows); + store.set_cursor("opencode", "parts", json!(format!("{}|{}", last.0, last.1))); + Ok(()) +} + +fn fnv(s: &str) -> u64 { let mut h = 0xcbf29ce484222325u64; for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(0x100000001b3); } h >> 11 } + +// ---------------- gemini (Antigravity) ---------------- +/// Step blob layout inferred by inspection (UNVERIFIED against any official schema): +/// step_type 14 = user input (text at field 19.3.1, else 19.2), 15 = model response (text at field 20.1; 20.3 is thinking, skipped), +/// timestamp at 5.1 {seconds,nanos}. +pub fn parse_gemini_step(step_type: i64, blob: &[u8]) -> Option<(String, &'static str, String)> { + use pb::{fields, Val}; + let sub = |b: &[u8], f: u32| -> Option> { fields(b)?.into_iter().find_map(|(n, v)| if n == f { if let Val::Bytes(x) = v { Some(x.to_vec()) } else { None } } else { None }) }; + let varint = |b: &[u8], f: u32| -> Option { fields(b)?.into_iter().find_map(|(n, v)| if n == f { if let Val::Varint(x) = v { Some(x) } else { None } } else { None }) }; + let meta = sub(blob, 5)?; + let t = sub(&meta, 1)?; + let ts = ts_from_secs_nanos(varint(&t, 1)? as i64, varint(&t, 2).unwrap_or(0) as u32)?; + let utf = |b: Vec| String::from_utf8(b).ok(); + match step_type { + 14 => { + let m = sub(blob, 19)?; + let text = sub(&m, 3).and_then(|x| sub(&x, 1)).and_then(utf).or_else(|| sub(&m, 2).and_then(utf))?; + Some((ts, "user", text)) + } + 15 => { + let m = sub(blob, 20)?; + let text = utf(sub(&m, 1)?)?; + Some((ts, "assistant", text)) + } + _ => None, + } +} + +fn gemini_db(store: &mut Store, host: &str, db: &Path, key: &str) -> std::io::Result<()> { + let session = file_stem(db); + let conn = match Connection::open_with_flags(db, OpenFlags::SQLITE_OPEN_READ_ONLY) { Ok(c) => c, Err(_) => return Ok(()) }; + let _ = conn.busy_timeout(std::time::Duration::from_secs(5)); + let cur = store.cursor("gemini", key).and_then(|v| v.as_i64()); + let after = cur.unwrap_or(-1); + let mut st = match conn.prepare("SELECT idx, step_type, step_payload FROM steps WHERE idx > ?1 AND step_type IN (14,15) ORDER BY idx") { Ok(s) => s, Err(_) => return Ok(()) }; + let mut rows = match st.query([after]) { Ok(r) => r, Err(_) => return Ok(()) }; + let mut max = after; + let mut recs = vec![]; + while let Ok(Some(r)) = rows.next() { + let idx: i64 = r.get(0).unwrap_or(0); + let ty: i64 = r.get(1).unwrap_or(0); + let blob: Vec = r.get(2).unwrap_or_default(); + max = max.max(idx); + if let Some((ts, role, text)) = parse_gemini_step(ty, &blob) { + if text.trim().is_empty() { continue; } + recs.push(Record { ts, agent: "gemini".into(), host: host.into(), session: session.clone(), role: role.into(), text, + model: None, cwd: None, src_path: key.into(), src_pos: idx as u64 }); + } + } + drop(rows); drop(st); + for r in recs { store.emit(r, cur.is_none())?; } + // Steps are appended with increasing idx, but a running step can be rewritten; keep cursor at max seen. + store.set_cursor("gemini", key, json!(max)); + Ok(()) +} + +fn copy_if_changed(store: &mut Store, src: &Path, dst: &Path, sig_key: &str) -> std::io::Result { + let m = std::fs::metadata(src)?; + let sig = format!("{}:{}", m.len(), m.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0)); + if store.cursor("gemini", sig_key).and_then(|v| v.as_str()) == Some(sig.as_str()) && dst.exists() { return Ok(false); } + if let Some(p) = dst.parent() { std::fs::create_dir_all(p)?; } + let tmp = dst.with_extension("part"); + std::fs::copy(src, &tmp)?; + std::fs::rename(&tmp, dst)?; + store.set_cursor("gemini", sig_key, json!(sig)); + Ok(true) +} + +pub fn collect_gemini(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { + let base = cfg.home.join(".gemini"); + for sub in ["antigravity-cli", "antigravity-ide", "antigravity"] { + let dir = base.join(sub).join("conversations"); + let Ok(rd) = std::fs::read_dir(&dir) else { continue }; + let mut dbs: Vec = rd.flatten().map(|e| e.path()).filter(|p| p.extension().map(|x| x == "db").unwrap_or(false)).collect(); + dbs.sort(); + for db in dbs { + let relp = format!("{sub}/conversations/{}", db.file_name().unwrap().to_string_lossy()); + let dst = store.root.join("raw/gemini").join(&cfg.host).join(&relp); + let mut changed_wal = false; + let changed0 = match copy_if_changed(store, &db, &dst, &format!("sig:{relp}")) { Ok(c) => c, Err(e) => { eprintln!("gemini raw copy {relp}: {e}"); true } }; + let wal = db.with_extension("db-wal"); + if wal.metadata().map(|m| m.len() > 0).unwrap_or(false) { + let wc = copy_if_changed(store, &wal, &dst.with_extension("db-wal"), &format!("sig:{relp}-wal")).unwrap_or(false); changed_wal = wc; + } + let k = format!("spark/{relp}"); + let changed = changed0 || changed_wal; + if changed || store.cursor("gemini", &k).is_none() { gemini_db(store, &cfg.host, &db, &k)?; } + } + } + let hist = base.join("antigravity-cli/history.jsonl"); + if hist.exists() { let _ = copy_if_changed(store, &hist, &store.root.join("raw/gemini").join(&cfg.host).join("antigravity-cli/history.jsonl"), "sig:history"); } + Ok(()) +} + +/// Read-only pull of the MacBook's Antigravity conversation DBs (ssh + scp), at most every `every_s` seconds. +pub fn pull_macbook(store: &mut Store, every_s: u64) -> std::io::Result<()> { + use std::process::Command; + let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + if let Some(t) = store.cursor("gemini", "macpull:last").and_then(|v| v.as_u64()) { if now < t + every_s { return Ok(()); } } + store.set_cursor("gemini", "macpull:last", json!(now)); + let ssh = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "-o", "ControlMaster=auto", "-o", "ControlPath=/tmp/agent-archive-mac-%C", "-o", "ControlPersist=60"]; + let listing = Command::new("ssh").args(ssh).arg("macbook") + .arg("for d in antigravity-cli antigravity-ide antigravity; do find ~/.gemini/$d/conversations -maxdepth 1 -type f \\( -name \"*.db\" -o -name \"*.db-wal\" \\) -exec stat -f \"$d %N %z %m\" {} + 2>/dev/null; done; find ~/.gemini/antigravity-cli -maxdepth 1 -name history.jsonl -exec stat -f \"hist %N %z %m\" {} + 2>/dev/null; true") + .output(); + let out = match listing { Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(), _ => { eprintln!("macbook unreachable, skipped"); return Ok(()); } }; + for l in out.lines() { + let p: Vec<&str> = l.split(' ').collect(); + if p.len() != 4 { continue; } + let (sub, path, size, mtime) = (p[0], p[1], p[2], p[3]); + let name = path.rsplit('/').next().unwrap_or(""); + let relp = if sub == "hist" { "antigravity-cli/history.jsonl".to_string() } else { format!("{sub}/conversations/{name}") }; + let dst = store.root.join("raw/gemini/macbook").join(&relp); + let sig = format!("{size}:{mtime}"); + let sk = format!("macsig:{relp}"); + if store.cursor("gemini", &sk).and_then(|v| v.as_str()) == Some(sig.as_str()) && dst.exists() { continue; } + if let Some(d) = dst.parent() { std::fs::create_dir_all(d)?; } + let tmp = dst.with_extension("part"); + let ok = Command::new("scp").args(ssh).arg("-q").arg(format!("macbook:{path}")).arg(&tmp).status().map(|s| s.success()).unwrap_or(false); + if ok { std::fs::rename(&tmp, &dst)?; store.set_cursor("gemini", &sk, json!(sig)); } else { let _ = std::fs::remove_file(&tmp); eprintln!("scp failed: {relp}"); } + } + Ok(()) +} + +/// Parse the already-pulled MacBook copies (raw/gemini/macbook/**/*.db). +pub fn collect_gemini_mac(store: &mut Store) -> std::io::Result<()> { + let base = store.root.join("raw/gemini/macbook"); + let mut dbs = vec![]; walk(&base, "db", &mut dbs); dbs.sort(); + for db in dbs { + let relp = rel(&db, &base); + let k = format!("macbook/{relp}"); + let m = std::fs::metadata(&db)?; + let sig = format!("{}:{}", m.len(), m.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0)); + let sk = format!("msig:{relp}"); + if store.cursor("gemini", &sk).and_then(|v| v.as_str()) == Some(sig.as_str()) { continue; } + gemini_db(store, "macbook", &db, &k)?; + store.set_cursor("gemini", &sk, json!(sig)); + } + Ok(()) +} diff --git a/src/core.rs b/src/core.rs new file mode 100644 index 0000000..31a2cda --- /dev/null +++ b/src/core.rs @@ -0,0 +1,255 @@ +//! Record schema, archive store (records, raw mirror, latest views, state cursors). +use chrono::{DateTime, SecondsFormat, TimeZone, Utc}; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::fs::{self, File, OpenOptions}; +use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; + +pub const LATEST_LINES: usize = 20000; +pub const TXT_MAX_CHARS: usize = 8000; +pub const AGENTS: [&str; 5] = ["claude", "codex", "opencode", "gemini", "muse"]; + +#[derive(Clone, Debug, PartialEq)] +pub struct Record { + pub ts: String, + pub agent: String, + pub host: String, + pub session: String, + pub role: String, + pub text: String, + pub model: Option, + pub cwd: Option, + pub src_path: String, + pub src_pos: u64, +} + +impl Record { + pub fn to_json(&self) -> Value { + json!({"ts":self.ts,"agent":self.agent,"host":self.host,"session":self.session, + "role":self.role,"text":self.text,"model":self.model,"cwd":self.cwd, + "src":{"path":self.src_path,"pos":self.src_pos}}) + } + pub fn from_json(v: &Value) -> Option { + let s = |k: &str| v.get(k).and_then(|x| x.as_str()).map(String::from); + Some(Record { + ts: s("ts")?, agent: s("agent")?, host: s("host")?, session: s("session")?, + role: s("role")?, text: s("text")?, model: s("model"), cwd: s("cwd"), + src_path: v.pointer("/src/path")?.as_str()?.to_string(), + src_pos: v.pointer("/src/pos")?.as_u64()?, + }) + } + pub fn date(&self) -> &str { &self.ts[..10] } + pub fn key(&self) -> u64 { + // FNV-1a over the identity (agent, host, session, role, src path, src pos). + let mut h: u64 = 0xcbf29ce484222325; + for part in [self.agent.as_str(), &self.host, &self.session, &self.role, &self.src_path] { + for b in part.bytes().chain(std::iter::once(0u8)) { h ^= b as u64; h = h.wrapping_mul(0x100000001b3); } + } + for b in self.src_pos.to_le_bytes() { h ^= b as u64; h = h.wrapping_mul(0x100000001b3); } + h + } + pub fn txt_line(&self) -> String { + let mut t: String = self.text.chars().take(TXT_MAX_CHARS).collect(); + if self.text.chars().count() > TXT_MAX_CHARS { t.push_str(" ...[truncated]"); } + let t = t.replace('\r', "").replace('\n', "\\n"); + let s8: String = self.session.chars().take(8).collect(); + format!("[{} {} {}] {}", self.ts, s8, self.role, t) + } +} + +/// Normalise an RFC3339 string to millisecond UTC "…Z". None if unparseable. +pub fn norm_ts(s: &str) -> Option { + DateTime::parse_from_rfc3339(s).ok().map(|d| d.with_timezone(&Utc).to_rfc3339_opts(SecondsFormat::Millis, true)) +} +pub fn ts_from_ms(ms: i64) -> Option { + Utc.timestamp_millis_opt(ms).single().map(|d| d.to_rfc3339_opts(SecondsFormat::Millis, true)) +} +pub fn ts_from_secs_nanos(s: i64, n: u32) -> Option { + Utc.timestamp_opt(s, n).single().map(|d| d.to_rfc3339_opts(SecondsFormat::Millis, true)) +} + +pub struct Store { + pub root: PathBuf, + state: HashMap, + state_dirty: HashSet, + seen: HashMap>, + pub fresh: VecDeque, // unused window staging + latest: HashMap>, + latest_dirty: HashSet, + pub emitted: HashMap, + appenders: HashMap, +} + +impl Store { + pub fn open(root: &Path) -> std::io::Result { + for d in ["records", "raw", "latest", "state"] { fs::create_dir_all(root.join(d))?; } + let mut s = Store { root: root.to_path_buf(), state: HashMap::new(), state_dirty: HashSet::new(), + seen: HashMap::new(), fresh: VecDeque::new(), latest: HashMap::new(), latest_dirty: HashSet::new(), + emitted: HashMap::new(), appenders: HashMap::new() }; + for a in AGENTS { + if let Ok(t) = fs::read_to_string(root.join("state").join(format!("{a}.json"))) { + if let Ok(v) = serde_json::from_str::(&t) { s.state.insert(a.to_string(), v); } + } + } + Ok(s) + } + + // ---- cursors ---- + pub fn cursor(&self, agent: &str, key: &str) -> Option<&Value> { self.state.get(agent)?.get(key) } + pub fn set_cursor(&mut self, agent: &str, key: &str, v: Value) { + let e = self.state.entry(agent.to_string()).or_insert_with(|| json!({})); + e[key] = v; + self.state_dirty.insert(agent.to_string()); + } + pub fn save_state(&mut self) -> std::io::Result<()> { + let dirty: Vec = self.state_dirty.drain().collect(); + for a in dirty { + atomic_write(&self.root.join("state").join(format!("{a}.json")), serde_json::to_string(&self.state[&a]).unwrap().as_bytes())?; + } + Ok(()) + } + + // ---- records ---- + /// Append a record. `check_dup`: consult the existing date file first (used when a source is re-read after state loss). + pub fn emit(&mut self, r: Record, check_dup: bool) -> std::io::Result { + let dir = self.root.join("records").join(&r.agent); + fs::create_dir_all(&dir)?; + let path = dir.join(format!("{}.jsonl", r.date())); + if check_dup && !self.seen.contains_key(&path) { + let mut set = HashSet::new(); + if let Ok(f) = File::open(&path) { + for l in BufReader::new(f).lines().map_while(Result::ok) { + if let Some(rec) = serde_json::from_str::(&l).ok().and_then(|v| Record::from_json(&v)) { set.insert(rec.key()); } + } + } + self.seen.insert(path.clone(), set); + } + if let Some(set) = self.seen.get_mut(&path) { + if !set.insert(r.key()) { return Ok(false); } + } + if !self.appenders.contains_key(&path) { + if self.appenders.len() > 64 { self.appenders.clear(); } + self.appenders.insert(path.clone(), OpenOptions::new().create(true).append(true).open(&path)?); + } + let mut line = serde_json::to_string(&r.to_json()).unwrap(); + line.push('\n'); + self.appenders.get_mut(&path).unwrap().write_all(line.as_bytes())?; + *self.emitted.entry(r.agent.clone()).or_insert(0) += 1; + let agent = r.agent.clone(); + let v = self.latest_for(&agent); + v.push((r.ts.clone(), r)); + if v.len() > LATEST_LINES * 2 { v.sort_by(|a, b| a.0.cmp(&b.0)); let n = v.len() - LATEST_LINES; v.drain(..n); } + self.latest_dirty.insert(agent); + Ok(true) + } + + fn latest_for(&mut self, agent: &str) -> &mut Vec<(String, Record)> { + if !self.latest.contains_key(agent) { + let v = load_tail(&self.root, agent, LATEST_LINES); + self.latest.insert(agent.to_string(), v); + } + self.latest.get_mut(agent).unwrap() + } + + /// End of pass: flush cursors and rewrite latest views for agents that got new records. + pub fn finish_pass(&mut self) -> std::io::Result<()> { + self.appenders.clear(); + self.seen.clear(); + let dirty: Vec = self.latest_dirty.drain().collect(); + for a in dirty { + let v = self.latest.get_mut(&a).unwrap(); + v.sort_by(|x, y| x.0.cmp(&y.0)); + if v.len() > LATEST_LINES { let n = v.len() - LATEST_LINES; v.drain(..n); } + let mut txt = String::new(); + let mut js = String::new(); + for (_, r) in v.iter() { + txt.push_str(&r.txt_line()); txt.push('\n'); + js.push_str(&serde_json::to_string(&r.to_json()).unwrap()); js.push('\n'); + } + atomic_write(&self.root.join("latest").join(format!("{a}.txt")), txt.as_bytes())?; + atomic_write(&self.root.join("latest").join(format!("{a}.jsonl")), js.as_bytes())?; + } + self.save_state() + } +} + +pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> { + if let Some(p) = path.parent() { fs::create_dir_all(p)?; } + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + { let mut f = File::create(&tmp)?; f.write_all(data)?; f.sync_all().ok(); } + fs::rename(&tmp, path) +} + +/// Last `n` records for an agent, read from the newest date files backwards. +pub fn load_tail(root: &Path, agent: &str, n: usize) -> Vec<(String, Record)> { + let dir = root.join("records").join(agent); + let mut files: Vec = fs::read_dir(&dir).map(|d| d.filter_map(|e| e.ok().map(|e| e.path())).collect()).unwrap_or_default(); + files.sort(); + let mut out: Vec<(String, Record)> = Vec::new(); + for f in files.iter().rev() { + let mut part = Vec::new(); + if let Ok(fh) = File::open(f) { + for l in BufReader::new(fh).lines().map_while(Result::ok) { + if let Some(r) = serde_json::from_str::(&l).ok().and_then(|v| Record::from_json(&v)) { part.push((r.ts.clone(), r)); } + } + } + out.extend(part); + if out.len() >= n { break; } + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + if out.len() > n { let k = out.len() - n; out.drain(..k); } + out +} + +/// Tail an append-only JSONL source from `cursor`: calls `f(line, byte_pos)` for every complete line, mirrors the +/// bytes verbatim into `raw_path`, and returns the new cursor. Returns (new_cursor, reset) where reset means the source +/// shrank and was re-read from 0. +pub fn tail_lines(src: &Path, raw_path: &Path, cursor: u64, mut f: F) -> std::io::Result<(u64, bool)> { + let len = fs::metadata(src)?.len(); + let (mut pos, reset) = if len < cursor { (0, true) } else { (cursor, false) }; + if len == pos { return Ok((pos, reset)); } + let mut fh = File::open(src)?; + fh.seek(SeekFrom::Start(pos))?; + let mut rd = BufReader::with_capacity(1 << 20, fh.take(len - pos)); + if let Some(p) = raw_path.parent() { fs::create_dir_all(p)?; } + let mut raw = OpenOptions::new().create(true).append(true).open(raw_path)?; + let mut raw_len = raw.metadata()?.len(); + let mut buf = Vec::new(); + loop { + buf.clear(); + let n = rd.read_until(b'\n', &mut buf)?; + if n == 0 { break; } + if buf.last() != Some(&b'\n') { break; } // partial last line: leave for next pass + let start = pos; + pos += n as u64; + // verbatim mirror: write only the bytes the mirror does not have yet + if pos > raw_len { + let skip = raw_len.saturating_sub(start) as usize; + raw.write_all(&buf[skip.min(buf.len())..])?; + raw_len = pos; + } + let line = String::from_utf8_lossy(&buf[..n - 1]); + let line = line.trim_end_matches('\r'); + if !line.is_empty() { f(line, start); } + } + Ok((pos, reset)) +} + +pub fn walk(dir: &Path, ext: &str, out: &mut Vec) { + let Ok(rd) = fs::read_dir(dir) else { return }; + for e in rd.flatten() { + let p = e.path(); + if p.is_dir() { walk(&p, ext, out); } + else if p.extension().map(|x| x == ext).unwrap_or(false) { out.push(p); } + } +} + +pub fn file_stem(p: &Path) -> String { p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default() } + +impl Store { + /// Number of real sources tracked for an agent (bookkeeping keys with a "xxx:" prefix are not counted). + pub fn state_keys(&self, agent: &str) -> usize { + self.state.get(agent).and_then(|v| v.as_object()).map(|o| o.keys().filter(|k| !k.contains(':') || k.as_str() == "parts").count()).unwrap_or(0) + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..aed68bc --- /dev/null +++ b/src/main.rs @@ -0,0 +1,302 @@ +mod collectors; +mod core; +mod pb; + +use collectors::*; +use core::*; +use regex::Regex; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +fn home() -> PathBuf { PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "/root".into())) } +fn default_root() -> PathBuf { + std::env::var("AGENT_ARCHIVE_ROOT").map(PathBuf::from).unwrap_or_else(|_| home().join("archive/agent-chats")) +} + +pub fn pass(store: &mut Store, cfg: &Cfg, mac: bool) { + type C = fn(&mut Store, &Cfg) -> std::io::Result<()>; + let steps: [(&str, C); 5] = [("claude", collect_claude), ("codex", collect_codex), ("opencode", collect_opencode), + ("gemini", collect_gemini), ("muse", collect_muse)]; + for (name, f) in steps { + if let Err(e) = f(store, cfg) { eprintln!("collector {name} failed: {e}"); } + } + if mac { + if let Err(e) = pull_macbook(store, 300) { eprintln!("macbook pull failed: {e}"); } + if let Err(e) = collect_gemini_mac(store) { eprintln!("gemini macbook parse failed: {e}"); } + } + if let Err(e) = store.finish_pass() { eprintln!("finish_pass failed: {e}"); } +} + +fn summary(store: &mut Store) -> String { + let mut v: Vec = store.emitted.iter().map(|(a, n)| format!("{a}={n}")).collect(); + v.sort(); + store.emitted.clear(); + v.join(" ") +} + +fn arg(args: &[String], name: &str) -> Option { + args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned()) +} + +fn status(root: &std::path::Path) { + let today = chrono::Utc::now().format("%Y-%m-%d").to_string(); + let st = Store::open(root).expect("open archive"); + println!("{:<9} {:<26} {:>12} {:>8} {}", "agent", "last record", "today", "sources", "preview"); + for a in AGENTS { + let tail = load_tail(root, a, 1); + let (last, prev) = tail.last().map(|(t, r)| (t.clone(), r.text.chars().take(80).collect::().replace('\n', " "))).unwrap_or(("-".into(), String::new())); + let todayn = std::fs::read_to_string(root.join("records").join(a).join(format!("{today}.jsonl"))).map(|s| s.lines().count()).unwrap_or(0); + let total: usize = std::fs::read_dir(root.join("records").join(a)).map(|d| d.flatten().filter_map(|e| std::fs::read_to_string(e.path()).ok()).map(|s| s.lines().count()).sum()).unwrap_or(0); + let sources = st.state_keys(a); + println!("{:<9} {:<26} {:>6}/{:<6} {:>8} {}", a, last, todayn, total, sources, prev); + } + println!("(today/total records)"); +} + +fn query(root: &std::path::Path, args: &[String]) { + let agent = arg(args, "--agent"); + let since = arg(args, "--since").unwrap_or_default(); + let re = arg(args, "--grep").map(|g| Regex::new(&g).unwrap_or_else(|e| { eprintln!("bad --grep: {e}"); std::process::exit(2) })); + let limit: usize = arg(args, "--limit").and_then(|l| l.parse().ok()).unwrap_or(50); + let json = args.iter().any(|a| a == "--json"); + let agents: Vec = match agent { Some(a) => vec![a], None => AGENTS.iter().map(|s| s.to_string()).collect() }; + let mut hits: Vec<(String, Record)> = vec![]; + for a in agents { + let dir = root.join("records").join(&a); + let mut files: Vec = std::fs::read_dir(&dir).map(|d| d.flatten().map(|e| e.path()).collect()).unwrap_or_default(); + files.sort(); + for f in files { + let day = f.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + if !since.is_empty() && day.as_str() < &since[..since.len().min(10)] { continue; } + let Ok(t) = std::fs::read_to_string(&f) else { continue }; + for l in t.lines() { + let Some(r) = serde_json::from_str(l).ok().and_then(|v| Record::from_json(&v)) else { continue }; + if !since.is_empty() && r.ts.as_str() < since.as_str() { continue; } + if let Some(re) = &re { if !re.is_match(&r.text) { continue; } } + hits.push((r.ts.clone(), r)); + } + } + } + hits.sort_by(|a, b| a.0.cmp(&b.0)); + let skip = hits.len().saturating_sub(limit); + for (_, r) in hits.into_iter().skip(skip) { + if json { println!("{}", serde_json::to_string(&r.to_json()).unwrap()); } else { println!("{} {}", r.agent, r.txt_line()); } + } +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let root = default_root(); + let cmd = args.first().map(|s| s.as_str()).unwrap_or("help"); + let cfg = Cfg { home: home(), host: "spark".into(), mac: true }; + match cmd { + "once" => { + let t = Instant::now(); + let mut st = Store::open(&root).expect("open archive"); + pass(&mut st, &cfg, cfg.mac && !args.iter().any(|a| a == "--no-mac")); + println!("once done in {:.1}s: {}", t.elapsed().as_secs_f64(), summary(&mut st)); + } + "collect" => { + let mut st = Store::open(&root).expect("open archive"); + loop { + pass(&mut st, &cfg, cfg.mac); + let s = summary(&mut st); + if !s.is_empty() { eprintln!("{} +{s}", chrono::Utc::now().format("%H:%M:%S")); } + std::thread::sleep(Duration::from_secs(10)); + } + } + "query" => query(&root, &args[1..]), + "status" => status(&root), + "debug-pb" => { let b = std::fs::read(&args[1]).expect("read file"); let mut s = String::new(); pb::dump(&b, 0, "", &mut s); print!("{s}"); } + _ => { + println!("agent-archive collect | once [--no-mac] | status | debug-pb FILE | query [--agent A] [--since TS] [--grep RE] [--limit N] [--json]\nroot: {} (override with AGENT_ARCHIVE_ROOT)", root.display()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn tmp(name: &str) -> PathBuf { + let p = std::env::temp_dir().join(format!("aa-test-{}-{}", name, std::process::id())); + let _ = fs::remove_dir_all(&p); + fs::create_dir_all(&p).unwrap(); + p + } + fn fixture(n: &str) -> String { fs::read_to_string(format!("{}/tests/fixtures/{n}", env!("CARGO_MANIFEST_DIR"))).unwrap() } + fn count(root: &std::path::Path, agent: &str) -> usize { + fs::read_dir(root.join("records").join(agent)).map(|d| d.flatten().map(|e| fs::read_to_string(e.path()).unwrap().lines().count()).sum()).unwrap_or(0) + } + + #[test] + fn claude_parser_keeps_text_only() { + let lines: Vec = fixture("claude.jsonl").lines().map(String::from).collect(); + let recs: Vec<_> = lines.iter().enumerate().flat_map(|(i, l)| parse_claude(l, "/x/eb18088a.jsonl", i as u64, "spark")).collect(); + assert_eq!(recs.len(), 2); + assert_eq!(recs[0].role, "user"); + assert_eq!(recs[1].text, "Looking now."); + assert_eq!(recs[1].model.as_deref(), Some("claude-opus-5-5")); + assert_eq!(recs[0].ts, "2026-09-26T09:35:16.500Z"); + assert_eq!(recs[0].session, "eb18088a"); + } + + #[test] + fn codex_parser_roles_and_session() { + let mut aux = serde_json::json!({}); + let p = "/s/rollout-2026-09-05T12-11-22-01a0728d-ae40-7261-b95b-8cdb98c5bc5f.jsonl"; + let recs: Vec<_> = fixture("codex.jsonl").lines().flat_map(|l| parse_codex(l, p, 0, "spark", &mut aux)).collect(); + let roles: Vec<&str> = recs.iter().map(|r| r.role.as_str()).collect(); + assert_eq!(roles, ["system", "user", "assistant"]); + assert_eq!(recs[0].session, "01a0728d-ae40-7261-b95b-8cdb98c5bc5f"); + assert_eq!(recs[2].model.as_deref(), Some("gpt-6-astra")); + } + + #[test] + fn muse_parser_user_and_assistant() { + let recs: Vec<_> = fixture("muse.jsonl").lines().flat_map(|l| parse_muse(l, "/m/session.jsonl", 0, "spark")).collect(); + assert_eq!(recs.len(), 2); + assert_eq!((recs[0].role.as_str(), recs[0].text.as_str()), ("user", "ls")); + assert_eq!((recs[1].role.as_str(), recs[1].text.as_str()), ("assistant", "225")); + assert!(recs[0].ts.starts_with("2026-09-20T")); + } + + // Blob built to the layout observed in a real Antigravity step (field numbers: 5.1 time, 19.3.1 user text, 20.1 reply text). + fn tag(f: u32, w: u32) -> Vec { let mut o = vec![]; let mut v = (f << 3) | w; loop { let c = (v & 0x7f) as u8; v >>= 7; if v == 0 { o.push(c); break; } o.push(c | 0x80); } o } + fn enc_len(f: u32, b: &[u8]) -> Vec { + let mut o = tag(f, 2); + let mut n = b.len(); + loop { let c = (n & 0x7f) as u8; n >>= 7; if n == 0 { o.push(c); break; } o.push(c | 0x80); } + o.extend_from_slice(b); o + } + fn enc_var(f: u32, mut v: u64) -> Vec { + let mut o = tag(f, 0); + loop { let c = (v & 0x7f) as u8; v >>= 7; if v == 0 { o.push(c); break; } o.push(c | 0x80); } + o + } + fn step(top: u32, inner: Vec) -> Vec { + let time = [enc_var(1, 1790836387), enc_var(2, 593377033)].concat(); + let meta = enc_len(1, &time); + [enc_var(1, 14), enc_len(5, &meta), enc_len(top, &inner)].concat() + } + + #[test] + fn gemini_step_user_and_assistant() { + let user = step(19, [enc_len(2, b"/plan raw"), enc_len(3, &enc_len(1, b" cleaned text"))].concat()); + let (ts, role, text) = parse_gemini_step(14, &user).unwrap(); + assert_eq!((role, text.as_str()), ("user", " cleaned text")); + assert_eq!(ts, "2026-10-01T06:33:07.593Z"); + let asst = step(20, [enc_len(1, b"the answer"), enc_len(3, b"thinking")].concat()); + let (_, role, text) = parse_gemini_step(15, &asst).unwrap(); + assert_eq!((role, text.as_str()), ("assistant", "the answer")); + assert!(parse_gemini_step(132, &asst).is_none()); + } + + #[test] + fn full_pass_incremental_and_dedupe_after_state_loss() { + let home = tmp("home"); + let root = tmp("root"); + let proj = home.join(".claude/projects/-p"); + fs::create_dir_all(&proj).unwrap(); + let f = proj.join("sess1.jsonl"); + let fx = fixture("claude.jsonl"); + fs::write(&f, &fx).unwrap(); + let cfg = Cfg { home: home.clone(), host: "spark".into(), mac: false }; + let mut st = Store::open(&root).unwrap(); + pass(&mut st, &cfg, false); + assert_eq!(count(&root, "claude"), 2); + // raw mirror is byte-identical + assert_eq!(fs::read_to_string(root.join("raw/claude/spark/-p/sess1.jsonl")).unwrap(), fx); + // latest views exist + let txt = fs::read_to_string(root.join("latest/claude.txt")).unwrap(); + assert!(txt.contains("[2026-09-26T09:35:16.500Z sess1 user] Check the live")); + // second pass: nothing new + pass(&mut st, &cfg, false); + assert_eq!(count(&root, "claude"), 2); + // append one complete line and one partial line + let mut more = fx.clone(); + let extra = "{\"type\":\"user\",\"message\":{\"role\":\"user\",\"content\":\"second\"},\"timestamp\":\"2026-09-26T10:00:00.000Z\"}\n"; + more.push_str(extra); + more.push_str("{\"type\":\"user\",\"mess"); + let more_complete_len = fx.len() + extra.len(); + fs::write(&f, &more).unwrap(); + pass(&mut st, &cfg, false); + assert_eq!(count(&root, "claude"), 3); + // lose all cursors: re-read must not duplicate records + fs::remove_dir_all(root.join("state")).unwrap(); + let mut st2 = Store::open(&root).unwrap(); + pass(&mut st2, &cfg, false); + assert_eq!(count(&root, "claude"), 3); + // raw never doubled either + assert!(fs::read_to_string(root.join("raw/claude/spark/-p/sess1.jsonl")).unwrap().starts_with(&fx)); + assert_eq!(fs::metadata(root.join("raw/claude/spark/-p/sess1.jsonl")).unwrap().len() as usize, more_complete_len); + } + + #[test] + fn opencode_collects_text_parts() { + let home = tmp("ochome"); + let root = tmp("ocroot"); + let d = home.join(".local/share/opencode"); + fs::create_dir_all(&d).unwrap(); + let c = rusqlite::Connection::open(d.join("opencode.db")).unwrap(); + c.execute_batch("create table session(id text primary key, directory text, model text); + create table message(id text primary key, session_id text, time_created integer, data text); + create table part(id text primary key, message_id text, session_id text, time_created integer, time_updated integer, data text); + insert into session values('ses_1','/home/x',null); + insert into message values('msg_1','ses_1',1790977000000,'{\"role\":\"user\",\"model\":{\"modelID\":\"m1\"}}'); + insert into message values('msg_2','ses_1',1790977001000,'{\"role\":\"assistant\",\"modelID\":\"m1\"}'); + insert into part values('prt_1','msg_1','ses_1',1790977000000,1790977000100,'{\"type\":\"text\",\"text\":\"hi there\"}'); + insert into part values('prt_2','msg_2','ses_1',1790977001000,1790977001100,'{\"type\":\"reasoning\",\"text\":\"think\"}'); + insert into part values('prt_3','msg_2','ses_1',1790977002000,1790977002100,'{\"type\":\"text\",\"text\":\"hello\"}');").unwrap(); + drop(c); + let cfg = Cfg { home, host: "spark".into(), mac: false }; + let mut st = Store::open(&root).unwrap(); + pass(&mut st, &cfg, false); + assert_eq!(count(&root, "opencode"), 2); + let recs = load_tail(&root, "opencode", 10); + assert_eq!(recs[0].1.text, "hi there"); + assert_eq!(recs[0].1.model.as_deref(), Some("m1")); + assert_eq!(recs[1].1.role, "assistant"); + pass(&mut st, &cfg, false); + assert_eq!(count(&root, "opencode"), 2); + } + + #[test] + fn gemini_db_pass() { + let home = tmp("gmhome"); + let root = tmp("gmroot"); + let d = home.join(".gemini/antigravity-cli/conversations"); + fs::create_dir_all(&d).unwrap(); + let c = rusqlite::Connection::open(d.join("conv-1.db")).unwrap(); + c.execute_batch("create table steps(idx integer primary key, step_type integer, step_payload blob);").unwrap(); + let u = step(19, enc_len(3, &enc_len(1, b"question"))); + let a = step(20, enc_len(1, b"answer")); + c.execute("insert into steps values(0,14,?1)", [u]).unwrap(); + c.execute("insert into steps values(1,15,?1)", [a]).unwrap(); + drop(c); + let cfg = Cfg { home, host: "spark".into(), mac: false }; + let mut st = Store::open(&root).unwrap(); + pass(&mut st, &cfg, false); + assert_eq!(count(&root, "gemini"), 2); + assert!(root.join("raw/gemini/spark/antigravity-cli/conversations/conv-1.db").exists()); + pass(&mut st, &cfg, false); + assert_eq!(count(&root, "gemini"), 2); + } + + #[test] + fn latest_window_is_capped_and_sorted() { + let root = tmp("latest"); + let mut st = Store::open(&root).unwrap(); + for i in 0..(LATEST_LINES + 50) { + let r = Record { ts: format!("2026-10-04T00:{:02}:{:02}.{:03}Z", (i / 60000) % 60, (i / 1000) % 60, i % 1000), agent: "claude".into(), host: "spark".into(), + session: "s".into(), role: "user".into(), text: format!("m{i}"), model: None, cwd: None, src_path: "p".into(), src_pos: i as u64 }; + st.emit(r, false).unwrap(); + } + st.finish_pass().unwrap(); + let t = fs::read_to_string(root.join("latest/claude.txt")).unwrap(); + assert_eq!(t.lines().count(), LATEST_LINES); + assert!(t.lines().last().unwrap().ends_with(&format!("m{}", LATEST_LINES + 49))); + assert!(!t.contains("] m0\n")); + } +} diff --git a/src/pb.rs b/src/pb.rs new file mode 100644 index 0000000..36eaacb --- /dev/null +++ b/src/pb.rs @@ -0,0 +1,86 @@ +//! Minimal protobuf wire-format walker (no schema). Used for Gemini/Antigravity step blobs. + +pub enum Val<'a> { + Varint(u64), + Bytes(&'a [u8]), + Fixed(#[allow(dead_code)] u64), +} + +pub fn varint(b: &[u8], i: &mut usize) -> Option { + let mut v = 0u64; + let mut shift = 0; + while *i < b.len() { + let c = b[*i]; + *i += 1; + v |= ((c & 0x7f) as u64) << shift; + if c & 0x80 == 0 { + return Some(v); + } + shift += 7; + if shift > 63 { + return None; + } + } + None +} + +/// Parse one message level. Returns None if the bytes are not a clean message. +pub fn fields(b: &[u8]) -> Option)>> { + let mut i = 0; + let mut out = Vec::new(); + while i < b.len() { + let tag = varint(b, &mut i)?; + let f = (tag >> 3) as u32; + if f == 0 { + return None; + } + match tag & 7 { + 0 => out.push((f, Val::Varint(varint(b, &mut i)?))), + 1 => { + let e = i.checked_add(8)?; + if e > b.len() { return None; } + out.push((f, Val::Fixed(u64::from_le_bytes(b[i..e].try_into().ok()?)))); + i = e; + } + 2 => { + let n = varint(b, &mut i)? as usize; + let e = i.checked_add(n)?; + if e > b.len() { return None; } + out.push((f, Val::Bytes(&b[i..e]))); + i = e; + } + 5 => { + let e = i.checked_add(4)?; + if e > b.len() { return None; } + out.push((f, Val::Fixed(u32::from_le_bytes(b[i..e].try_into().ok()?) as u64))); + i = e; + } + _ => return None, + } + } + Some(out) +} + +pub fn dump(b: &[u8], depth: usize, path: &str, out: &mut String) { + if let Some(fs) = fields(b) { + for (f, v) in fs { + let p = format!("{path}.{f}"); + match v { + Val::Varint(n) => out.push_str(&format!("{p} = {n}\n")), + Val::Fixed(n) => out.push_str(&format!("{p} = fixed {n}\n")), + Val::Bytes(x) => { + if depth < 8 && !x.is_empty() && fields(x).is_some() && std::str::from_utf8(x).map(|s| s.chars().any(|c| c.is_control() && c != '\n')).unwrap_or(true) { + out.push_str(&format!("{p} {{\n")); + dump(x, depth + 1, &p, out); + out.push_str("}\n"); + } else if let Ok(s) = std::str::from_utf8(x) { + let t: String = s.chars().take(100).collect(); + out.push_str(&format!("{p} = {:?}\n", t)); + } else { + out.push_str(&format!("{p} = <{} bytes>\n", x.len())); + } + } + } + } + } +} diff --git a/tests/fixtures/claude.jsonl b/tests/fixtures/claude.jsonl new file mode 100644 index 0000000..90270f1 --- /dev/null +++ b/tests/fixtures/claude.jsonl @@ -0,0 +1,4 @@ +{"type":"permission-mode","permissionMode":"auto","sessionId":"eb18088a-ea95-4eef-910c-672c8a35ffc3"} +{"parentUuid":null,"type":"user","message":{"role":"user","content":"Check the live GitHub state against the M15 report."},"timestamp":"2026-09-26T09:35:16.500Z","cwd":"/home/drakestapleton","sessionId":"eb18088a-ea95-4eef-910c-672c8a35ffc3"} +{"type":"assistant","message":{"model":"claude-opus-5-5","role":"assistant","content":[{"type":"thinking","thinking":"hmm"},{"type":"text","text":"Looking now."},{"type":"tool_use","id":"toolu_x","name":"Bash","input":{"command":"ls"}}]},"timestamp":"2026-09-26T09:35:20.100Z","cwd":"/home/drakestapleton"} +{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_x","content":"a\nb"}]},"timestamp":"2026-09-26T09:35:21.000Z"} diff --git a/tests/fixtures/codex.jsonl b/tests/fixtures/codex.jsonl new file mode 100644 index 0000000..71fc9ae --- /dev/null +++ b/tests/fixtures/codex.jsonl @@ -0,0 +1,7 @@ +{"timestamp":"2026-09-05T17:11:57.983Z","ordinal":0,"type":"session_meta","payload":{"id":"01a0728d-ae40-7261-b95b-8cdb98c5bc5f","cwd":"/home/drakestapleton"}} +{"timestamp":"2026-09-05T17:11:58.000Z","type":"turn_context","payload":{"model":"gpt-6-astra","cwd":"/home/drakestapleton"}} +{"timestamp":"2026-09-05T17:12:00.000Z","type":"response_item","payload":{"type":"message","role":"developer","content":[{"type":"input_text","text":"sandbox rules"}]}} +{"timestamp":"2026-09-05T17:12:01.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"hello codex"}]}} +{"timestamp":"2026-09-05T17:12:02.000Z","type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hello Drake"}]}} +{"timestamp":"2026-09-05T17:12:03.000Z","type":"response_item","payload":{"type":"custom_tool_call","name":"x"}} +{"timestamp":"2026-09-05T17:12:03.500Z","type":"event_msg","payload":{"type":"token_count"}} diff --git a/tests/fixtures/muse.jsonl b/tests/fixtures/muse.jsonl new file mode 100644 index 0000000..e75ac54 --- /dev/null +++ b/tests/fixtures/muse.jsonl @@ -0,0 +1,4 @@ +{"retained_frame":"session_permission_transaction","frame_schema_version":1,"outer_log_ordinal":1,"children":[]} +{"schema_version":1,"id":"a","stream":{"kind":"session","id":"01a0bec6-c930-7192-972d-7a3bf42d2552"},"sequence":12,"recorded_at":1789907129524992,"record_type":"event","payload_type":"runtime.user_intent.accepted","payload":{"surface":"main","semantic_kind":{"kind":"chat"},"model_messages":[{"content":[{"kind":"text","text":"ls"}]}]}} +{"schema_version":1,"id":"b","stream":{"kind":"session","id":"01a0bec6-c930-7192-972d-7a3bf42d2552"},"sequence":30,"recorded_at":1789907139524992,"record_type":"event","payload_type":"runtime.session","payload":{"event":{"kind":"assistant_message_committed","message_id":"m","response_id":null,"text":"225"},"kind":"run","run_id":"r"}} +{"schema_version":1,"id":"c","stream":{"kind":"session","id":"01a0bec6-c930-7192-972d-7a3bf42d2552"},"sequence":31,"recorded_at":1789907149524992,"record_type":"event","payload_type":"run.model.configured","payload":{}}