Expand description
File activity shared by consumers such as Peekback. No viewer, terminal, Markdown, or global state-directory dependency.
§session-activity
A Rust library for file activity observed during coding-agent sessions, such
as Claude Code and Codex. It preserves the evidence behind each path and
retains history independently of the calling application. It knows no
particular agent: the caller turns its agent’s hooks or transcripts into
FileEvents.
It is developed alongside Peekback and published separately on crates.io;
it has no GUI, Markdown, terminal, or Peekback runtime dependency.
crates.io · API reference · Changelog
Add it to your Rust project with cargo add session-activity@0.3, or edit
your manifest:
[dependencies]
session-activity = "0.3"Requires Rust 1.87 or newer. The supported storage/maintenance platforms are
macOS and Linux. The library is not currently validated on Windows, where
maintenance is unavailable. To install the Peekback application instead, use
cargo install peekback --locked on Apple Silicon macOS.
The library owns:
SessionKey: anAgentIdnamespace chosen by the caller (lowercase ASCII letters, digits and-) plus the agent’s native session ID.FileEvent: versioned file metadata, operation, outcome, timestamp, source, working directory, optional tool call ID, rename origin, and the sessions that were working concurrently when a scan observed the file.Store: retained event batches under a caller-supplied directory.Store::append_newappends only events not already retained, for callers that capture the same evidence repeatedly.Store::sessionsandStore::read_all: enumerate and read retained history across every agent namespace, independently of a live-session registry.scan_report: bounded filesystem scans and completeness diagnostics from caller-supplied roots, each with an inclusive modification-time window (scanreturns only the events).FileActivity::scan_onlyandFileActivity::possibly_shared: whether only scans saw a file, and whether one did while another session was working in the same place.Store::maintain: preview or apply compaction and timestamp retention.files: grouping observations by path without losing their evidence.
Peekback owns the hook command, hook and transcript decoding for each agent, live session registry, terminal metadata, choice of scan roots, Markdown filtering, and labels. The library does not read a global configuration or choose its own storage location.
use session_activity::{AgentId, SessionKey, Store, files};
// The caller chooses the directory; the library never discovers global state.
let store = Store::new(std::env::temp_dir().join("my-app-session-activity"));
let session = SessionKey {
agent: AgentId::new("codex")?,
session_id: "native-session-id".into(),
};
let report = store.read(&session)?;
for warning in &report.warnings {
eprintln!("{}: {}", warning.path.display(), warning.message);
}
let touched_files = files(report.events);To record an observation, build it with FileEvent::new and pass it to
store.append(&session, &events). Only metadata is stored, never document
contents.
From a repository checkout, run the consumer example:
cargo run -p session-activity --example inspect -- /path/to/activity codex SESSION_IDIt prints retained file summaries as JSON and reports incomplete history on stderr. The example reads a store; it does not install hooks or start a viewer.
§API and data compatibility
Versions within one minor release retain compatible public API and storage
behavior. Breaking API changes require a new minor version while the crate is
pre-1.0. Storage schema versions are independent of crate versions: events are
written with schema 2 (SCHEMA_VERSION), which adds concurrent, schema 1
events remain readable, and checkpoints use version 1. Unsupported schemas produce errors or batch
warnings rather than being silently interpreted as current data. Preserve old
history until a documented migration exists.
Events describe observations, not a complete audit of a session’s filesystem
effects. Errors use anyhow::Result; error message wording is diagnostic and is
not a stable API. Store::events is strict, while Store::read returns healthy
events with warnings. A malformed authoritative checkpoint remains a hard error.
Operations are read, write (create or replace), create, modify, delete,
rename, and observed. Rename events carry the destination in path and origin in previous_path.
File queries include both, even when either path no longer exists.
Sources distinguish hooks, transcript records, legacy registry paths, and project/scratchpad/memory scans. The caller sets an event’s outcome when its source establishes one; otherwise it stays unknown. A scan only observes file modification times. Consumers decide which operations, outcomes, and sources count for their use case.
reconcile connects known outcomes to unknown observations for the same
session, call ID, operation, and paths. Conflicting known outcomes remain
visible, and scan observations are never promoted to attributed writes.
It collapses retries within each evidence source, retaining observations from
both hooks and transcripts. Calls without IDs remain separate. files applies
this automatically; consumers filtering failed operations should call
reconcile before filtering. The retained raw event history is unchanged.
Storage uses one immutable JSON batch per hook invocation under
ROOT/AGENT/SESSION_ID/. Private temporary files are renamed into place after
writing, so concurrent writers do not replace each other’s observations. Files
are synced before publication; on Unix, newly created directories and the
directory containing the published batch are also synced. This strengthens
crash durability within the filesystem’s sync guarantees.
Temporary files left by an interrupted writer are ignored. Store::read
returns healthy events plus warnings naming invalid, oversized, unreadable,
or unsupported batches, leaving damaged data untouched. Store::events
remains strict and returns an error if any batch is incomplete. Both reads
and writes validate session identity, schema, absolute paths, and rename
origins; batches are limited to 16 MiB. append_new reads and appends under
one exclusive lock and compares every field except the schema version and
concurrent, so evidence captured again, such as a transcript parsed at every
turn, is kept once. History is retained unless the owner
explicitly applies retention; session exit does not delete event files. Retried hook
calls can produce repeated observations, identifiable by tool call IDs when
the agent supplies them. Reconciled file queries collapse those retries.
store.maintain(&session, None, false) previews compaction; pass true as the
last argument to apply it. Supplying Some(unix_seconds) also drops events
strictly older than that cutoff. The report includes batch/event counts and
cleanup warnings. A persistent cutoff, exposed by Store::retained_from,
filters subsequent appends and reads; callers importing transient observations
should apply it too. Later maintenance can advance but never lower the cutoff,
so a cutoff in the future is rejected. Maintenance of an absent session is a
no-op.
Maintenance preserves raw events without reconciliation and refuses any
damaged batch or unexpected .json file in the session directory. It writes synced .pack chunks (each at most 16 MiB), then
atomically publishes a synced .checkpoint before deleting original batches.
The checkpoint identifies covered originals, making interrupted cleanup safe
to retry; uncommitted packs are ignored. A malformed checkpoint is a hard error
because the authoritative history cannot safely be inferred.
On Unix, readers and appenders hold shared advisory locks; maintenance holds an exclusive lock. Lock files must not be deleted while the store is in use. Maintenance is unsupported on other platforms. All consumers must understand the checkpoint format before maintenance is applied: older binaries see only uncompacted batches. Reads and maintenance still load the full retained history into memory; compaction reduces filesystem overhead, not event parsing cost.
store.sessions() returns sorted session keys plus enumeration warnings. It
skips namespace/session symlinks and reports invalid directory names or access
failures. store.read_all() returns all healthy retained events and warnings;
a damaged checkpoint is reported for its session while other sessions remain
available. Pass its events to files to group by path across sessions; each
event retains its agent/session identity. These queries include compacted and
ended sessions, honor retention cutoffs, and do not scan the filesystem. read_all loads all retained history into memory and locks each session
separately, so it is not a globally atomic snapshot of concurrent activity.
Paths are resolved lexically against the session cwd, including . and ..;
symlink aliases are not unified. The library stores metadata, not file content
snapshots, and exists reflects the filesystem at query time. Scans skip hidden
and build directories and other checkouts (a directory below a root with its
own .git directory, or a .git file pointing into worktrees/), while
submodules stay included, do not follow symlink
directories, and share a caller-supplied entry budget across roots. Callers should avoid scanning / or home.
scan_report reports visited entries, budget exhaustion, depth limits, and
path-specific I/O warnings. Missing optional roots are ignored; other failures
are reported. Completeness is relative to the caller’s roots and exclusions,
not proof that every session-touched file was found.
cargo test -p session-activityStructs§
- AgentId
- The namespace of the agent that produced a session, such as
claude. The caller chooses it; the library only requires lowercase ASCII letters, digits and-, since it names a directory. - Batch
Warning - File
Activity - File
Event - A metadata-only observation. Renames use
pathfor the destination andprevious_pathfor the source. Unknown outcomes are never promoted by a scan. - Maintenance
Report - Read
Report - Scan
Report - Completion metadata for a bounded scan. An empty result alone cannot tell the caller whether there were no matching files or the scan was incomplete.
- Scan
Root - Scan
Warning - Session
Key - Session
Report - Store
- An append-only store of metadata-only batches, namespaced by agent/session. Each hook writes its own batch then renames it atomically. Concurrent hooks cannot overwrite each other, and readers never see a partially written batch.
Enums§
Constants§
- SCHEMA_
VERSION - Schema 2 adds
FileEvent::concurrent. Schema 1 batches remain readable.
Functions§
- files
- Group observations by path; retain deleted paths and both sides of renames. Filtering by extension, outcome, or operation belongs to the consumer.
- reconcile
- Reconcile outcome evidence for the same tool invocation and remove retries. Missing call IDs are not sufficient evidence that two observations are the same operation. Conflicting known outcomes remain visible to the consumer.
- resolve_
path - Lexical normalization preserves paths even after deletion and never needs to follow symlinks or read the file.
- scan
- scan_
report - Hidden/build directories and nested checkouts are excluded by policy, symlink directories are not followed, and all roots share the entry budget. A nested checkout is usually another worktree with its own sessions. Missing optional roots are normal; other read/metadata errors are reported with their paths.
- valid_
id