### Install and run initial CLI commands Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/getting-started.md Installs the ai-hist CLI globally and runs initial discovery and listing commands. Requires Node.js 20 or 22. The default database is ~/.local/share/ai-hist/ai-history.db; set AI_HIST_DB to override. ```bash npm install --global ai-hist ai-hist sessions discover --limit 100 ai-hist sessions list --limit 100 ``` -------------------------------- ### Run the rust-consumer example Source: https://github.com/agentworkforce/relayhistory/blob/main/examples/rust-consumer/README.md Run the example from the `examples/rust-consumer` directory. It stages transcripts, opens a SessionStore, runs a sync, walks the catalog, prints usage rollups, and drains changes_since. Exits non-zero if the sweep did not catalogue a staged session or no session reported usage. ```sh cd examples/rust-consumer cargo run ``` -------------------------------- ### Cold Start Sequence with discoverSessions, listSessionCatalog, and hydrateSession Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/architecture.md A typical cold start that discovers local sessions, lists the catalog, and hydrates the first session. This sequence is safe because no read operation triggers discovery or sync. ```TypeScript await discoverSessions({ limit: 100, scope: 'local' }); const sessions = await listSessionCatalog({ limit: 100, scope: 'all' }); await hydrateSession({ source: sessions[0].source, sessionId: sessions[0].sessionId }); ``` -------------------------------- ### Watermark::START Source: https://github.com/agentworkforce/relayhistory/blob/main/CHANGELOG.md Replay from the start of the database. ```APIDOC ## Watermark::START ### Description Replay from the start of the database. ### Method Constant ### Value - A watermark constant representing the start of the database. ``` -------------------------------- ### Install ai-hist 1.0 npm package and verify binary path Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/native-sdk-migration.md Remove standalone/curl-installed ai-hist binaries and install the npm package globally. Before installing, remove any standalone executable reported by the first `type -a` (commonly `~/.local/bin/ai-hist`). After installing, verify the first result points into npm's global installation rather than the old binary. ```bash npm uninstall --global ai-hist-mcp type -a ai-hist npm install --global ai-hist ai-hist-mcp type -a ai-hist ``` -------------------------------- ### Install and use ai-hist CLI Source: https://github.com/agentworkforce/relayhistory/blob/main/README.md Install the ai-hist CLI globally with npm, then run the bare command to discover and index recent sessions on first use. Use the search command to query the indexed sessions. The bare command leaves an already-populated database alone; run 'ai-hist sync' for a full re-ingest. ```sh npm install -g ai-hist ai-hist # first run discovers and indexes your recent sessions ai-hist search "the thing i was working on" ``` -------------------------------- ### Rust example: forget_evidence and compact Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/sourcing-sdk.md Example of using forget_evidence to keep evidence for selected sessions and then compacting the store. ```rust use ai_hist::{CompactOptions, ForgetOptions, ForgetScope}; // Keep evidence for the selected sessions only. let report = store.forget_evidence(ForgetScope::AllExcept(selected), ForgetOptions::default())?; if report.sessions > 0 { store.compact(CompactOptions::default())?; } ``` -------------------------------- ### Install OMP writer dependency and run capture Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/history-providers/fixtures/omp/README.md Install the checksum-pinned @oh-my-pi/pi-coding-agent@18.9.2 into a temporary prefix, then run capture.mjs to produce writer-session.jsonl and writer-fork.jsonl. After a native debug build and SDK build, run surface-proof.mjs to check public SDK discovery, CLI search, and MCP capabilities. ```sh npm install --prefix /private/tmp/omp-writer-phase2 --ignore-scripts @oh-my-pi/pi-coding-agent@18.9.2 bun plans/history-providers/fixtures/omp/capture.mjs /private/tmp/omp-writer-phase2/node_modules/@oh-my-pi/pi-coding-agent /private/tmp/omp-synthetic-output # after this checkout's native debug build and SDK build: node plans/history-providers/fixtures/omp/surface-proof.mjs . ``` -------------------------------- ### Install SDK package Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/getting-started.md Installs the ai-hist SDK package via npm. ```bash npm install ai-hist ``` -------------------------------- ### Install OpenClaw and run capture fixture Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/history-providers/openclaw.md Run these commands to install a specific OpenClaw version and execute the capture fixture script. The script writes synthetic sessions using plugin-SDK APIs into an isolated state directory, producing SQL dumps and oracle JSON files. ```sh npm install --prefix ~/Projects/scratch-openclaw/writers/ --ignore-scripts openclaw@ OPENCLAW_WRITER=~/Projects/scratch-openclaw/writers/ node crates/ai-hist/src/providers/openclaw/capture_fixture.mjs ``` -------------------------------- ### ai-hist sessions discover and list CLI examples Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Shows the default discover command, the --all variant with remote connectors, list commands with various filters, keyset pagination with --before-ms, and machine-readable JSON output forms. ```bash # Refresh from local provider locations (the default). ai-hist sessions discover ai-hist sessions discover --local # Run every configured discovery adapter: local adapters plus any # configured remote connectors (see source-plugins.md). ai-hist sessions discover --all --limit 20 # Read back what the catalog holds — no provider file is opened. ai-hist sessions list ai-hist sessions list --remote --limit 100 --source codex --source claude ai-hist sessions list --all --limit 100 # Page backwards by recency (keyset, not OFFSET). ai-hist sessions list --limit 50 --before-ms 1781949900000 # Machine-readable forms. ai-hist sessions list --json # one JSON object ai-hist sessions discover --json # JSONL: sessions, diagnostics, summary ``` -------------------------------- ### SDK usage example Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/getting-started.md Imports and uses the SDK functions discoverSessions, listSessionCatalog, and search. The scope parameter accepts 'local', 'remote', or 'all'. ```ts import { discoverSessions, listSessionCatalog, search } from 'ai-hist'; await discoverSessions({ limit: 100, scope: 'local' }); const sessions = await listSessionCatalog({ limit: 100, scope: 'all' }); const matches = await search('authentication', { scope: 'all' }); ``` -------------------------------- ### Install cargo-public-api and update public API snapshot Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/releasing.md Commands to install cargo-public-api (requires a nightly toolchain for rustdoc JSON) and to regenerate the public API snapshot. The public-api CI job fails on any difference or if any line names a rusqlite type. ```bash cargo install cargo-public-api --locked # once; needs a nightly toolchain for rustdoc JSON node scripts/check-public-api.mjs --update ``` -------------------------------- ### Use ai-hist SessionStore and SessionQuery Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/releasing.md Example Rust code showing how to open a SessionStore, sync it, and retrieve evidence for changed sessions. Uses default features which expose SessionStore, evidence structs, Source, and Error. ```rust use ai_hist::{SessionQuery, SessionStore}; let store = SessionStore::open(Default::default())?; let report = store.sync(Default::default())?; for changed in &report.changed { let _evidence = store.session(changed, SessionQuery::default())?; } ``` -------------------------------- ### sessions list --json output example Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Example JSON output from the 'sessions list --json' command. The output is a single object (not an array) that includes contract_version, scope, sessions array, and next_cursor. Keys are snake_case; arrays like models, workspace_roots, and locations are always arrays, and other absent values are null. ```jsonc { "contract_version": 6, "scope": "local", "sessions": [ { "source": "codex", "session_id": "0198c2ad-codex", "cwd": "/Users/you/Projects/api", "git_branch": "feature/retries", "first_activity_ms": 1782039600000, "last_activity_ms": 1782039603000, "first_prompt": "make the backoff configurable", "last_assistant_text": null, "title": "Make retry backoff configurable", "session_kind": null, "models": ["gpt-5-codex"], "originator": "codex_cli_rs", "agent_version": "0.148.0", "repo_url": "git@github.com:acme/api.git", "initial_commit": "abc1234def", "workspace_roots": ["/Users/you/Projects/api"], "raw_path": "/Users/you/.codex/sessions/2026/06/21/rollout-codex.jsonl", "source_stamp": "v2:1788042670103317900:569", "discovery_state": "shallow", "project_key": "github.com/acme/api", "project_key_method": "remote", "locations": ["local"], "from_cache": true } ], "next_cursor": { "last_activity_ms": 1782039603000, "source": "codex", "session_id": "0198c2ad-codex" } } ``` -------------------------------- ### SessionStore::watch Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/public-api.txt Starts watching for changes using the given options, returning a WatchHandle. ```APIDOC ## SessionStore::watch ### Description Starts watching for changes using the given options. ### Method `pub fn watch(&self, ai_hist::WatchOptions) -> core::result::Result` ### Parameters - `options` (WatchOptions) - Required - Options for watching. ### Returns - `Result` - A handle to the watch. ``` -------------------------------- ### Human-readable output example for sessions discover Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Shows the human-readable output when not using --json. Diagnostics go to stderr, leaving stdout clean. The final line summarizes the run. ```text 2026-06-21 11:00 codex local shallow 0198c2ad-codex /Users/you/Projects/api make the backoff configurable 2026-06-20 10:05 claude local shallow 3f6c1b7a-claude /Users/you/Projects/api add a retry to the http client 2 session(s): 0 discovered, 2 unchanged (0 file(s) opened, 0 shallow read(s)); requested scope: local, connector locations run: local ``` -------------------------------- ### JSONL output example for sessions discover --json Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Shows the three line types in order: session rows, diagnostics, and a summary. The summary is always emitted, even when all providers fail. Diagnostics are separate lines and never inside the summary object. ```jsonc // 0..n session rows, in global recency order (newest first) {"type": "session", "source": "codex", "session_id": "0198c2ad-codex", "from_cache": false, /* …same fields as above… */ } // 0..n non-fatal failures — one provider or one malformed session {"type": "diagnostic", "source": "grok", "locator": "/Users/you/.grok/sessions/…/chat_history.jsonl", "error": "…"} // exactly one closing summary — emitted even when every provider failed, // so a consumer always sees the reason before the non-zero exit { "type": "summary", "contract_version": 6, "scope": "local", "locations_run": ["local"], "discovered": 2, "skipped_unchanged": 0, "providers": { "claude": {"candidates": 1, "discovered": 1, "skipped_unchanged": 0, "failed": false}, "codex": {"candidates": 1, "discovered": 1, "skipped_unchanged": 0, "failed": false}, "cursor": {"candidates": 0, "discovered": 0, "skipped_unchanged": 0, "failed": false}, "grok": {"candidates": 0, "discovered": 0, "skipped_unchanged": 0, "failed": false}, "opencode": {"candidates": 0, "discovered": 0, "skipped_unchanged": 0, "failed": false} }, "exempt_sources": [], "counters": { "candidates_enumerated": 2, "shallow_reads": 2, "skipped_unchanged": 0, "files_opened": 2, "bytes_read": 978, "provider_queries": 0, "records_inspected": 0 } } ``` -------------------------------- ### SessionStore::watch_discover Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/public-api.txt Starts watching for discovery changes using the given options, returning a WatchHandle. ```APIDOC ## SessionStore::watch_discover ### Description Starts watching for discovery changes using the given options. ### Method `pub fn watch_discover(&self, ai_hist::WatchOptions) -> core::result::Result` ### Parameters - `options` (WatchOptions) - Required - Options for watching discovery. ### Returns - `Result` - A handle to the watch. ``` -------------------------------- ### ai-hist CLI: search, resume, and pack commands Source: https://github.com/agentworkforce/relayhistory/blob/main/README.md Shows the three primary ai-hist commands: search to find sessions across all harnesses, resume to print the native resume command, and pack to generate a token-budgeted context pack. The output examples illustrate expected results. ```sh ai-hist search "auth rewrite" # → matches across every codex/claude/cursor session on this machine ai-hist resume "auth rewrite" # → prints `codex resume 29284179-c09f-44f2-b9ec-16f678dc1832` ai-hist pack "auth rewrite" --tokens 1500 # → a token-budgeted context pack, ready to paste into another agent ``` -------------------------------- ### Reproduce Muse 1.4.7 export with capture.py Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/history-providers/fixtures/baseline/muse-1.4.7/README.md Run this shell command to reproduce the export projection from the Muse 1.4.7 fixture. It requires the path to the Muse binary and an output path for the JSON projection. The command is intended for use without installing or launching an agent. ```sh python3 plans/history-providers/fixtures/baseline/muse-1.4.7/capture.py \ --binary /path/to/muse --out /private/tmp/muse-export-projection.json ``` -------------------------------- ### Reproduce baseline capture with capture.py Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/history-providers/fixtures/baseline/opencode-1.18.31/README.md Run this command to reproduce the baseline capture using a separately installed pinned binary. The command invokes capture.py with the binary path and output directory. Note that native timestamps and isolated directory metadata change on recapture; compare message/part IDs, roles, text, tool IDs and payloads, not whole-file digests. ```sh python3 plans/history-providers/fixtures/baseline/opencode-1.18.31/capture.py \ --binary /path/to/opencode --out /private/tmp/opencode-baseline-recapture ``` -------------------------------- ### Rust: Open store, sync, query sessions, and consume changes Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/README.md Shows the core ai-hist Rust API: open a SessionStore, sync to get changed sessions, query session evidence and catalog rows, and incrementally consume changes with a consumer watermark. The change cursor only advances on commit(). ```rust use ai_hist::{CatalogQuery, SessionQuery, SessionStore}; fn main() -> Result<(), ai_hist::Error> { let store = SessionStore::open(Default::default())?; let report = store.sync(Default::default())?; for changed in &report.changed { if let Some(evidence) = store.session(changed, SessionQuery::default())? { println!("{} requests, {} tool results", evidence.requests.len(), evidence.tool_results.len()); } } for row in store.sessions(CatalogQuery::default()) { let row = row?; println!("{} {} {:?}", row.source, row.session_id, row.project_key); } // Incremental: everything since this consumer's last commit, oldest first. let query = ai_hist::ChangeQuery::default().consumer("my-ingest"); let mut changes = store.changes_since(ai_hist::Watermark::CONSUMER, query)?; for change in changes.by_ref() { let _change = change?; // `Upsert` or `Delete` of `change.key`; `columns` is the stored row } changes.commit()?; // the cursor moves only here Ok(()) } ``` -------------------------------- ### Completed Cursor hydration capability and coverage Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Example JSON response from a completed Cursor hydration showing partial capability, coverage limited to history, and a HYDRATION_PARTIAL_COVERAGE diagnostic naming the missing kinds. ```json { "capability": "partial", "coverage": ["history"], "diagnostics": [{ "code": "HYDRATION_PARTIAL_COVERAGE", "message": "cursor evidence covers history; this hydration produces no session_event, tool_call, file_edit, relationship" }] } ``` -------------------------------- ### JSON request for discover operation Source: https://github.com/agentworkforce/relayhistory/blob/main/plugins/provider-sources/rust/README.md Example JSON request for the discover operation, specifying connectorId 'codex-cloud', connectorInstance 'work', source 'codex', and limit 100. ```json {"version":1,"operation":"discover","args":{"connectorId":"codex-cloud","connectorInstance":"work","source":"codex","limit":100}} ``` -------------------------------- ### Register remote source plugins with HistoryPluginRegistry Source: https://github.com/agentworkforce/relayhistory/blob/main/sdk-ts/README.md Shows how to create a HistoryPluginRegistry, register a plugin for 'claude-web', and use it with discoverSessions and sync. Remote acquisition requires an explicitly loaded plugin registry; installing a package does not register it. Cached reads like stats with scope 'remote' do not require login. ```ts import { HistoryPluginRegistry } from 'ai-hist'; import { createHistoryPlugin } from '@relayhistory/provider-sources'; const plugins = new HistoryPluginRegistry(); plugins.register(createHistoryPlugin({connectors:['claude-web']})); await discoverSessions({ scope:'remote', plugins, sourceConnectors:['claude-web'] }); await sync({ scope:'all', plugins, sourceConnectors:[] }); // local adapters only const cached = await stats({ scope:'remote' }); // no login required ``` -------------------------------- ### Run ai-hist MCP server with npx Source: https://github.com/agentworkforce/relayhistory/blob/main/README.md Starts the ai-hist MCP server. The server exposes tools like search_history, list_sessions, get_session_events, get_session_tool_calls, get_session_file_edits, get_session_tree, history_stats, and relay tools. It reads local history and optional source plugins from AI_HIST_PLUGIN_CONFIG. ```sh npx -y ai-hist-mcp ``` -------------------------------- ### Run validation and oracle commands Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/history-providers/fixtures/omp/README.md Run the validation test and oracle script from the repository root. Requires Bun 1.3.14 or compatible runtime with Bun.JSONL.parseChunk; installed Bun 1.3.4 cannot execute the reader. The oracle refuses changed upstream source hashes and does not execute loadSessionMessagesReadOnly, migrations, or filesystem blob-resolution. ```sh node --test plans/history-providers/fixtures/omp/validate.test.mjs bun plans/history-providers/fixtures/omp/oracle.mjs /path/to/pinned/oh-my-pi ``` -------------------------------- ### Query session relationships, tree, and descendant events Source: https://github.com/agentworkforce/relayhistory/blob/main/sdk-ts/README.md Use getSessionRelationships to get relationship details, getSessionTree to get a pre-order tree, and sessionEventsIncludingDescendants to iterate over events from descendant sessions. The example shows how to call these functions with a source and sessionId. ```typescript import { getSessionRelationships, getSessionTree, sessionEventsIncludingDescendants, } from 'ai-hist'; const { asParent, asChild, continuity, capabilities } = await getSessionRelationships({ source: 'codex', sessionId: rootId, }); const tree = await getSessionTree({ source: 'codex', sessionId: rootId, maxDepth: 8 }); for await (const event of sessionEventsIncludingDescendants({ source: 'codex', sessionId: rootId })) { // event.sessionId is the session that actually produced the event: a // child's event is never rewritten as the parent's. consume(event); } ``` -------------------------------- ### Opening a SessionStore with StoreOptions Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/sourcing-sdk.md Shows how to open a `SessionStore` using `StoreOptions::default()` with chainable setters for `db_path`, `home`, and `read_only`. The `?` operator propagates errors. ```rust let store = SessionStore::open( StoreOptions::default() .db_path("/srv/history/ai-history.db") .home("/home/agent") .read_only(true), )?; ``` -------------------------------- ### Run benchmark commands (CI gate, full profile, manual store) Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/benchmarks.md Commands to run the benchmark suite: the fast CI gate, the full published matrix with a release build and 100 MB store, and a manual store generation for hand inspection. The --target-bytes flag sets the whole store size; when opencode is a source, its SQLite database takes a share of that budget. ```bash # the fast subset, exactly as CI runs it on every pull request node scripts/benchmark-sync.mjs --gate # the published matrix (release build, 100 MB store) cargo test --workspace --all-features --test sync_bench --release --no-run node scripts/benchmark-sync.mjs --profile full --output sync-bench.md # one store on disk, to poke at by hand node scripts/gen-synthetic-history.mjs --out /tmp/bench-home --target-bytes 104857600 ``` -------------------------------- ### Run benchmark-sync.mjs with full profile Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/benchmarks.md Command to run the benchmark harness with the full profile, a large session size of 1 MiB, and two repeats. Used to measure cold and incremental sync phases. ```bash node scripts/benchmark-sync.mjs --profile full --large-session-bytes 1048576 --repeat 2 ``` -------------------------------- ### Run benchmark-sync.mjs for full profile Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/benchmarks.md Runs the sync benchmark with the full profile and a large session size of 1 MiB. Used to measure cold sync, incremental sync, unchanged sync, and hydration phases on the 100 MB store. ```bash node scripts/benchmark-sync.mjs --profile full --large-session-bytes 1048576 ``` -------------------------------- ### StoredRow::get Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/public-api.txt Gets a value from the stored row by key. ```APIDOC ## StoredRow::get ### Description Gets a value from the stored row by key. ### Method get ### Signature pub fn get(&self, &str) -> core::option::Option<&serde_json::value::Value> ### Parameters - **key** (&str) - Required - The key to look up. ### Returns - **Option<&serde_json::Value>** - The value if present, otherwise None. ``` -------------------------------- ### Handoff intent JSON example Source: https://github.com/agentworkforce/relayhistory/blob/main/mcp-package/README.md Example of the intent field returned by create_handoff. This JSON object is sent as structured delivery metadata with kind="handoff", and its intent value is used as the DM text. The intent is self-describing and instructs the receiver to call resume_handoff. ```json {"source":"codex","session_id":"abc","intent":"Resume this handoff: call resume_handoff(source=codex, session_id=abc) via the ai-hist MCP, then continue: continue the fix","origin_agent":"sender","origin_user":"user-id"} ``` -------------------------------- ### Run discovery benchmark Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Runs the benchmark harness for the session catalog. It builds a synthetic multi-provider archive, runs catalog operations and a full sync, and prints a measurement table. Assertions are operation counts, not wall-clock timings. ```bash cargo test -p ai-hist-cli --test discovery_bench -- --ignored --nocapture ``` -------------------------------- ### Benchmark Commands for Sync and Hydration Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/benchmarks.md Commands to run the sync benchmark suite. The first command builds the benchmark, the second runs the full profile with 1 MB large session bytes, and the third and fourth run the full profile with 50 MB and 200 MB large session bytes respectively, targeting specific phases. ```bash cargo test --workspace --all-features --test sync_bench --release --no-run ``` ```bash node scripts/benchmark-sync.mjs --profile full --large-session-bytes 1048576 ``` ```bash node scripts/benchmark-sync.mjs --profile full --target-bytes 1048576 \ --large-session-bytes 52428800 --phases cold_sync,hydrate_cold,hydrate_unchanged ``` ```bash node scripts/benchmark-sync.mjs --profile full --target-bytes 1048576 \ --large-session-bytes 209715200 --phases cold_sync,hydrate_cold,hydrate_unchanged ``` -------------------------------- ### Changes Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/public-api.txt Iterator over changes. Provides methods to get the current position, head watermark, consumer, and to commit the current position. ```APIDOC ## Changes ### Description Iterator over change records. ### Methods - **commit(&self)** -> Result - Commits the current position. - **consumer(&self)** -> Option<&str> - Returns the consumer identifier. - **head(&self)** -> Watermark - Returns the head watermark. - **position(&self)** -> Watermark - Returns the current position. - **next(&mut self)** -> Option> - Advances the iterator. ``` -------------------------------- ### Run core tests Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/009-local-history-cloud-boundary.md Run the core test suite to verify the migration. This command should exit with code 0. ```bash cargo test -p ai-hist-core ``` -------------------------------- ### Run default benchmark Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/benchmarks.md Runs the benchmark suite against the default RelayHistory database. Requires a release build of the native addon; a debug build will be refused. ```bash npm run benchmark ``` -------------------------------- ### FileEdit Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/public-api.txt Represents a file edit with metadata such as file path, lines added/removed, and tool information. Provides a method to get the raw structured patch. ```APIDOC ## FileEdit ### Description Represents a file edit operation with metadata. ### Fields - **cwd** (Option) - Current working directory. - **file_path** (String) - Path of the edited file. - **git_branch** (Option) - Git branch. - **lines_added** (Option) - Number of lines added. - **lines_removed** (Option) - Number of lines removed. - **message_id** (Option) - Message identifier. - **structured_patch** (Option) - Structured patch data. - **tool_name** (Option) - Name of the tool used. - **tool_use_id** (String) - Tool use identifier. - **ts_ms** (Option) - Timestamp in milliseconds. - **user_modified** (Option) - Whether the user modified the edit. ### Methods #### raw_structured_patch(&self) -> Option<&str> Returns the raw structured patch as a string slice if present. ``` -------------------------------- ### CatalogSession Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/public-api.txt Struct representing a cataloged session. Contains metadata such as session_id, source, models, locations, and activity timestamps. Provides a method to get a SessionRef. ```APIDOC ## CatalogSession ### Description Metadata for a single session in the catalog. ### Fields - **agent_version** (Option) - Agent version. - **cwd** (Option) - Current working directory. - **discovery_state** (DiscoveryState) - Discovery state. - **first_activity_ms** (Option) - First activity timestamp (ms). - **first_prompt** (Option) - First prompt text. - **git_branch** (Option) - Git branch. - **initial_commit** (Option) - Initial commit hash. - **last_activity_ms** (Option) - Last activity timestamp (ms). - **last_assistant_text** (Option) - Last assistant text. - **locations** (Vec) - File locations. - **models** (Vec) - Model identifiers. - **originator** (Option) - Originator identifier. - **project_key** (Option) - Project key. - **project_key_method** (Option) - Method used to determine project key. - **raw_path** (Option) - Raw path. - **repo_url** (Option) - Repository URL. - **session_id** (String) - Unique session identifier. - **session_kind** (Option) - Session kind. - **source** (Source) - Source of the session. - **source_stamp** (Option) - Source stamp. - **title** (Option) - Session title. - **workspace_roots** (Vec) - Workspace root paths. ### Methods - **session_ref(&self)** -> SessionRef - Returns a reference to the session. ``` -------------------------------- ### Run engine tests Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/009-local-history-cloud-boundary.md Run the engine test suite to verify the migration. This command should exit with code 0. ```bash cargo test -p ai-hist-engine ``` -------------------------------- ### JSON request for send operation Source: https://github.com/agentworkforce/relayhistory/blob/main/plugins/provider-sources/rust/README.md Example JSON request for the send operation, posting a message to a Devin cloud session with a session ID and message text. ```json {"version":1,"operation":"send","args":{"connectorId":"devin-cloud","sessionId":"<32-hex or devin-prefixed>","message":""}} ``` -------------------------------- ### Open SessionStore, sync, and query sessions in Rust Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/sourcing-sdk.md Opens a SessionStore with default options, syncs the corpus, prints sweep and change counts, then iterates over catalog sessions and prints usage tokens for messages that have usage data. Uses ai_hist::Error for error handling. ```rust use ai_hist::{CatalogQuery, SessionQuery, SessionStore, StoreOptions, SyncOptions}; fn main() -> Result<(), ai_hist::Error> { let store = SessionStore::open(StoreOptions::default())?; let report = store.sync(SyncOptions::default())?; println!("swept={} changed={}", report.swept, report.changed.len()); for row in store.sessions(CatalogQuery::default()) { let row = row?; let Some(evidence) = store.session(&row.session_ref(), SessionQuery::default())? else { continue; }; for message in &evidence.messages { if let Some(usage) = &message.usage { println!("{} {:?} in={} out={}", row.session_id, message.request_id, usage.input_tokens, usage.output_tokens); } } } Ok(()) } ``` -------------------------------- ### Iterate export with exportHistory Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/export.md TypeScript example using the exportHistory async iterator. It reads one consistent snapshot of the store as it stood when export began, closing it when finished or stopped. ```ts import { exportHistory } from 'ai-hist'; for await (const record of exportHistory(selection, { dbPath })) { await consume(record); } ``` -------------------------------- ### Run OpenCode fixed-limit scaling benchmark Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/benchmarks.md Command to run only the opencode_fixed_limit_scaling_report benchmark test. Use --ignored and --nocapture flags. ```bash cargo test -p ai-hist-cli --test discovery_bench \ opencode_fixed_limit_scaling_report -- --ignored --nocapture ``` -------------------------------- ### JSON plugin configuration for provider-sources Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/source-plugins.md Configuration object for the @relayhistory/provider-sources plugin, specifying connectors and instance ID. Used in a config file (e.g., history.json) resolved beside installed node_modules. ```json {"plugins":[{"module":"@relayhistory/provider-sources","options":{"connectors":["claude-web"],"instanceId":"personal"}}]} ``` -------------------------------- ### CLI commands for discovery, listing, sync, search, recent, and events Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/getting-started.md Shows common CLI commands with scope flags. Note that sessions list, search, and recent only query cached rows; a missing database produces an empty result. Combining scope flags is an error. ```bash ai-hist sessions discover --local --limit 100 ai-hist sessions list --all --limit 20 ai-hist sync --local ai-hist search "authentication" --all --limit 20 ai-hist recent --remote --limit 20 ai-hist events SESSION_ID --limit 200 ``` -------------------------------- ### Download and run capture script Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/history-providers/copilot.md Downloads the pinned Copilot CLI tarball, extracts it, and runs capture.py with the binary and output directory. The script verifies the binary, uses an empty COPILOT_HOME, runs only offline importer and specific RPCs, and refuses an existing output directory. ```sh curl -fsSL https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.95.tgz -o /tmp/copilot-1.0.95.tgz mkdir -p /tmp/copilot-1.0.95 && tar -xzf /tmp/copilot-1.0.95.tgz -C /tmp/copilot-1.0.95 python3 crates/ai-hist/src/providers/copilot/capture.py --cli /tmp/copilot-1.0.95/package/copilot --out /tmp/copilot-recapture-432 ``` -------------------------------- ### Replace unbounded event reads with page or async iterator Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/native-sdk-migration.md Use a page or async iterator for event reads to avoid unbounded reads. The example shows `getSessionEventsPage` with a limit and `sessionEvents` as an async iterator. ```ts const page = await getSessionEventsPage(id, { limit: 200 }); for await (const event of sessionEvents(id, { limit: 200 })) consume(event); ``` -------------------------------- ### jq: Capture tool-name dialect for tool_use blocks Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Run to capture the real tool-name dialect for your model. ```bash jq -r '.message.content[]? | select(.type=="tool_use") | .name' … | sort | uniq -c ``` -------------------------------- ### GET /v1/delivery/records Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/009-delivery-protocol.md Retrieves current retained records with deterministic opaque keyset pagination, optionally filtered by kind, source, or session identity. Requires rth:read permission and an X-RelayHistory-Expected-Account header matching the authenticated account hash. ```APIDOC ## GET /v1/delivery/records ### Description Retrieves current retained records with deterministic opaque keyset pagination. Optionally filters by kind, source, or session identity. Tombstones are excluded by default but can be included when explicitly requested for synchronization purposes. ### Method GET ### Endpoint /v1/delivery/records ### Parameters #### Headers - **X-RelayHistory-Expected-Account** (string) - Required - The account hash that must match the authenticated account. #### Query Parameters - **kind** (string) - Optional - Filter by record kind. - **source** (string) - Optional - Filter by source identity. - **session** (string) - Optional - Filter by session identity. - **includeTombstones** (boolean) - Optional - When true, includes tombstones in the response for synchronization purposes. - **cursor** (string) - Optional - Opaque keyset pagination cursor. ### Response #### Success Response (200) Returns the current retained records with pagination metadata. The response includes a cursor for subsequent pages if more records exist. #### Response Example { "records": [ { "id": "string", "kind": "string", "source": "string", "session": "string", "payload": {} } ], "nextCursor": "string" } ``` -------------------------------- ### Create a local source plugin with createHistoryPlugin Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/source-plugins.md Declares a local source plugin with location: 'local' and absolute roots. The discover method returns observations with source, session_id, raw_path, and source_stamp; hydrate returns a SourceEvidenceSnapshot. Registration requires a nonempty roots list of absolute paths, and all reported raw_paths must resolve inside them. ```javascript export function createHistoryPlugin({ root }) { return { sources: [{ id: 'host-app', instanceId: 'default', location: 'local', roots: [root], supportedSources: ['claude'], async discover() { /* { observations: [{ source, session_id, raw_path, source_stamp }] } */ }, async hydrate(observation) { /* a SourceEvidenceSnapshot */ }, }] }; } ``` -------------------------------- ### jq: Confirm top-level key set is exactly role,message Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Run against ~/.cursor/projects/*/agent-transcripts//.jsonl to confirm the top-level key set is exactly role,message and record any extra key. ```bash jq -r 'keys|join(",")' … | sort -u ``` -------------------------------- ### ai-hist watch usage examples Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/agent-integration.md Shows various invocations of ai-hist watch with options for debounce, leading edge, polling interval, and disabling filesystem events. Watch attaches to provider session roots and falls back to polling when filesystem events are unavailable. ```bash ai-hist watch # fs events, quiet change swept at once, 200ms window, 30s backstop ``` ```bash ai-hist watch --debounce-ms 500 # collapse bursts over a longer window ``` ```bash ai-hist watch --no-leading-edge # wait out the window before every sweep ``` ```bash ai-hist watch --interval 30 # polling cadence when fs events are off ``` ```bash ai-hist watch --no-fsevents # poll only ``` -------------------------------- ### StoreOptions::home Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/public-api.txt Sets the home directory for the store. ```APIDOC ## StoreOptions::home ### Description Sets the home directory for the store. ### Method home ### Signature pub fn home(self, impl core::convert::Into) -> Self ### Parameters - **path** (impl Into) - Required - The home directory path. ### Returns - **Self** - The updated StoreOptions. ``` -------------------------------- ### Benchmark with database override Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/benchmarks.md Runs the benchmark with a custom database path, either via the --db option or the AI_HIST_DB environment variable. The -- separator is required before benchmark-specific options. ```bash npm run benchmark -- --output=foo.md --db=/path/to/ai-history.db ``` ```bash AI_HIST_DB=/path/to/ai-history.db npm run benchmark -- --output=foo.md ``` -------------------------------- ### Verify commands for Stage 2 Source: https://github.com/agentworkforce/relayhistory/blob/main/plans/009-local-history-cloud-boundary.md Run these commands to verify the changes in Stage 2. Both must exit with code 0. ```bash cargo test -p ai-hist-engine ``` ```bash npm --prefix sdk-ts test ``` -------------------------------- ### CLI commands for remote discovery and sync Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/source-plugins.md Commands to discover sessions and sync history with a source connector, and to sync without source connectors. The --no-source-connectors flag disables remote sources. ```sh ai-hist sessions discover --remote --config history.json --source-connector claude-web ai-hist sync --all --config history.json --source-connector claude-web ai-hist sync --all --no-source-connectors ``` -------------------------------- ### SessionStore::open Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/public-api.txt Opens a session store with the given options. Returns a Result containing the SessionStore or an Error. ```APIDOC ## SessionStore::open ### Description Opens a session store with the given options. ### Method `pub fn open(ai_hist::StoreOptions) -> core::result::Result` ### Parameters - `options` (StoreOptions) - Required - Options for opening the store. ### Returns - `Result` - The opened SessionStore or an error. ``` -------------------------------- ### compact(CompactOptions { lock_timeout_ms }) Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/sourcing-sdk.md Merges the full-text index, rewrites the file with VACUUM, and truncates the WAL to return freed pages and delete markers to the volume. It holds the SyncRunLock during the rewrite, so concurrent sync operations may return Error::SyncLocked. It requires about twice the live data plus 512 MiB free space and returns Error::InsufficientSpace before writing if space is insufficient. ```APIDOC ## compact(CompactOptions { lock_timeout_ms }) ### Description Merges the full-text index, rewrites the file with VACUUM, and truncates the WAL to return freed pages and delete markers to the volume. It holds the SyncRunLock during the rewrite, so concurrent sync operations may return Error::SyncLocked. It requires about twice the live data plus 512 MiB free space and returns Error::InsufficientSpace before writing if space is insufficient. ### Method compact ### Parameters #### Options - **lock_timeout_ms** (integer) - Required - Timeout in milliseconds for acquiring the lock. ### Behavior - Deletes nothing and migrates nothing. - Space check is the first thing after taking the lock, so refusal comes before any write. - Holds the SyncRunLock for the rewrite, so a sync in that time returns Error::SyncLocked once its own lock_timeout_ms runs out. - A watch tick reports `contended` and retries; `hydrate` and `discover` wait in SQLite's busy handler. - Run it when a pause in writes is acceptable. ### Errors - **Error::InsufficientSpace** - Returned before writing anything when the required free space is not available. - **Error::SyncLocked** - Returned to a concurrent sync when its own lock_timeout_ms runs out. ``` -------------------------------- ### jq: Confirm message keys (content only) Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Run to confirm content is the only key under message, or capture id/model/usage if your build writes them. ```bash jq -r '.message|keys|join(",")' … | sort -u ``` -------------------------------- ### getSourceCapabilities(source) Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Answers, from the provider tables alone, the evidence kinds a hydration of that source covers, whether it can ever report 'full', and what its records establish about delegation. ```APIDOC ## getSourceCapabilities(source) ### Description Answers, from the provider tables alone, the evidence kinds a hydration of that source covers, whether it can ever report 'full', and what its records establish about delegation. ### Method Native (napi) function ### Parameters - **source** (string) - Required - The source identifier. ### Returns - **capabilities** (object) - The capabilities object, same as returned by `getSessionRelationships`. ``` -------------------------------- ### Rust: Build turn-to-config map from markers Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/sourcing-sdk.md Iterates markers in rollout order, tracking the current turn_context payload and mapping each turn_id to the configuration it ran under. Used to associate each turn with its effective configuration. ```rust // turn id -> the turn_context payload it ran under, in rollout order. let line = |uid: &str| uid.split_once(':').and_then(|(n, _)| n.parse::().ok()); let mut markers: Vec<&Marker> = evidence.markers.iter().collect(); markers.sort_by_key(|m| line(&m.marker_uid)); let mut current: Option<&serde_json::Value> = None; let mut configs: HashMap<&str, Option<&serde_json::Value>> = HashMap::new(); for marker in markers { if marker.kind == "turn_context" { current = marker.payload.as_ref(); } let Some(turn) = marker.turn_id.as_deref() else { continue }; if marker.kind == "turn_context" { configs.insert(turn, current); } else { configs.entry(turn).or_insert(current); } } ``` -------------------------------- ### Source::ALL Source: https://github.com/agentworkforce/relayhistory/blob/main/CHANGELOG.md Lists every source. ```APIDOC ## Source::ALL ### Description Lists every source. ### Method Constant ### Value - A list of all sources. ``` -------------------------------- ### discoverSessions(options?) Source: https://github.com/agentworkforce/relayhistory/blob/main/docs/session-catalog.md Runs a shallow scan of sessions and returns the rows plus a summary. The CLI renders the same collected result as JSONL when line-oriented records are more convenient. ```APIDOC ## discoverSessions(options?) ### Description Runs a shallow scan of sessions and returns the rows plus a summary. The CLI renders the same collected result as JSONL when line-oriented records are more convenient. ### Method Native (napi) function ### Parameters - **options** (object) - Optional - Configuration object with the following fields: - **scope** (string) - Optional - Scope filter. - **sources** (array) - Optional - List of sources. - **limit** (number) - Optional - Maximum number of results. - **beforeMs** (number) - Optional - Timestamp filter for entries before this time. - **after** (string) - Optional - Cursor from the previous page's `nextCursor`. ### Returns - **rows** (array) - List of session rows. - **summary** (object) - Summary of the scan. ``` -------------------------------- ### Run fixture corpus tests Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/tests/fixtures/README.md Run the fixture corpus test suite with all features enabled. This stages each fixture into an isolated provider HOME and writes canonical JSON dumps to tests/snapshots. ```sh cargo test -p ai-hist --all-features --test fixture_corpus ``` -------------------------------- ### CompactOptions Source: https://github.com/agentworkforce/relayhistory/blob/main/crates/ai-hist/public-api.txt Options for database compaction. Contains lock_timeout_ms. ```APIDOC ## CompactOptions ### Description Options for compacting the database. ### Fields - **lock_timeout_ms** (u64) - Lock timeout in milliseconds. ```