API Reference¶
Core data types, discovery functions, and the search pipeline used by every surface (CLI, TUI, MCP).
Core data¶
-
agentgrep.SearchScopeProvenance¶agentgrep.SearchScopeProvenance¶
alias of
Literal[‘inferred’, ‘explicit’]
-
agentgrep.SourceScanOutcome¶agentgrep.SourceScanOutcome¶
alias of
Literal[‘completed’, ‘bounded’, ‘unsupported’, ‘failed’, ‘cancelled’]
-
class agentgrep.PrivatePath¶class agentgrep.PrivatePath¶
Bases:
PosixPathPath subclass that hides account names in textual output.
str()andrepr()collapse the home directory to~, another account’s home (another user, or a WSL distro’s home seen from Windows) to~as well, and a Windows profile to%USERPROFILE%/%APPDATA%/%LOCALAPPDATA%(seeagentgrep.wsl.display_host_path()). The home directory inside an agent’s encoded project folder (-home-<user>-work) shows as-~-work(seeredact_encoded_paths()).os.fspath(), equality, and hashing keep using the real path, so aPrivatePathopens the file it names and compares equal to the plain path of that file.Examples
>>> import os, pathlib >>> from agentgrep import PrivatePath >>> home = pathlib.Path.home() >>> str(PrivatePath(home / "notes.txt")) '~/notes.txt' >>> os.fspath(PrivatePath(home / "notes.txt")) == str(home / "notes.txt") True >>> PrivatePath(home / "notes.txt") == home / "notes.txt" True
-
agentgrep.format_display_path(path, *, directory=False)¶agentgrep.format_display_path(path, *, directory=False)¶
Return a privacy-safe display path.
-
class agentgrep.BackendSelection¶class agentgrep.BackendSelection¶
Bases:
objectSelected optional subprocess backends.
-
class agentgrep.SearchQuery¶class agentgrep.SearchQuery¶
Bases:
objectCompiled search configuration.
compiledcarries the parsed-query predicates fromagentgrep.query. WhenNone(the default), the engine takes its legacy code path — pure-text queries and flag-only invocations stay on the fast path with no extra evaluation cost. When set,iter_search_eventsconsultscompiled.source_predicateto prune sources before any file is opened, andmatches_record()consultscompiled.record_predicateafter the existing text match.match_surfacelets line-oriented callers such asgreprequire a match in record text while fuzzy search and filtering can keep using the metadata-rich haystack.origin_filtercarries explicit CLI/MCP project filters outside the compiled query so plain text searches keep the legacy fast path.
-
class agentgrep.RecordOrigin¶class agentgrep.RecordOrigin¶
Bases:
objectProject/workspace origin attached to a normalized record.
Every field is independently optional: a store may record a branch and nothing else, or only a digest of a directory it never wrote out. All-
Noneis the empty originis_empty()reports.
-
class agentgrep.SourceHandle¶class agentgrep.SourceHandle¶
Bases:
objectA discovered, parseable source file or SQLite database.
-
class agentgrep.SearchRecord¶class agentgrep.SearchRecord¶
Bases:
objectNormalized prompt/history record.
-
class agentgrep.FindRecord¶class agentgrep.FindRecord¶
Bases:
objectNormalized discovery record for
agentgrep find.
-
class agentgrep.ProjectContext¶class agentgrep.ProjectContext¶
Bases:
objectBest-effort description of the invoking project.
-
agentgrep.detect_project_context(cwd=None)¶agentgrep.detect_project_context(cwd=None)¶
Detect the current project without spawning subprocesses.
The detector only walks upward from
cwdlooking for.git. It reads.git/HEADdirectly when present, and supports both normal repositories and worktrees whose.gitis agitdir:pointer file.- Parameters:
- Return type:
Search control and progress¶
-
class agentgrep.SearchControl¶class agentgrep.SearchControl¶
Bases:
objectThread-safe cooperative controls for an active search.
-
class agentgrep.SearchProgress¶class agentgrep.SearchProgress¶
Bases:
ProtocolProgress reporter used by search internals.
-
class agentgrep.NoopSearchProgress¶class agentgrep.NoopSearchProgress¶
Bases:
objectSilent search progress reporter.
-
class agentgrep.ConsoleSearchProgress¶class agentgrep.ConsoleSearchProgress¶
Bases:
objectHuman progress reporter for potentially long searches.
-
class agentgrep.SearchRuntime¶class agentgrep.SearchRuntime¶
Bases:
objectReusable, explicit runtime state for one search frontend/session.
Search result contract¶
Use run_search_result() when completion semantics matter. Its
RunSummary owns the normalized request, requested and
completed effort, primary status and conditions, outcome, coverage,
diagnostics, and next actions. Structured serializers place counts and timing
in stats; they do not read a RunSummary.statistics attribute.
-
agentgrep.RunState¶agentgrep.RunState¶
Type alias.
Type aliases are created through the type statement:
type Alias = int
In this example, Alias and int will be treated equivalently by static type checkers.
At runtime, Alias is an instance of TypeAliasType. The __name__ attribute holds the name of the type alias. The value of the type alias is stored in the __value__ attribute. It is evaluated lazily, so the value is computed only if the attribute is accessed.
Type aliases can also be generic:
type ListOrSet[T] = list[T] | set[T]
In this case, the type parameters of the alias are stored in the __type_params__ attribute.
See PEP 695 for more information.
-
agentgrep.SearchOutcome¶agentgrep.SearchOutcome¶
Type alias.
Type aliases are created through the type statement:
type Alias = int
In this example, Alias and int will be treated equivalently by static type checkers.
At runtime, Alias is an instance of TypeAliasType. The __name__ attribute holds the name of the type alias. The value of the type alias is stored in the __value__ attribute. It is evaluated lazily, so the value is computed only if the attribute is accessed.
Type aliases can also be generic:
type ListOrSet[T] = list[T] | set[T]
In this case, the type parameters of the alias are stored in the __type_params__ attribute.
See PEP 695 for more information.
-
agentgrep.results.DiagnosticSeverity¶agentgrep.results.DiagnosticSeverity¶
Type alias.
Type aliases are created through the type statement:
type Alias = int
In this example, Alias and int will be treated equivalently by static type checkers.
At runtime, Alias is an instance of TypeAliasType. The __name__ attribute holds the name of the type alias. The value of the type alias is stored in the __value__ attribute. It is evaluated lazily, so the value is computed only if the attribute is accessed.
Type aliases can also be generic:
type ListOrSet[T] = list[T] | set[T]
In this case, the type parameters of the alias are stored in the __type_params__ attribute.
See PEP 695 for more information.
-
class agentgrep.NormalizedSearchRequest¶class agentgrep.NormalizedSearchRequest¶
Bases:
objectFrontend-neutral request values applied by the engine.
-
class agentgrep.RunStatus¶class agentgrep.RunStatus¶
Bases:
objectPrimary terminal state plus retained secondary conditions.
-
class agentgrep.RunCoverage¶class agentgrep.RunCoverage¶
Bases:
objectAggregate source and record coverage for one search.
-
class agentgrep.RunDiagnostic¶class agentgrep.RunDiagnostic¶
Bases:
objectOne privacy-safe lifecycle warning or error.
-
class agentgrep.SearchRequestPatch¶class agentgrep.SearchRequestPatch¶
Bases:
objectBounded changes for starting a related search request.
-
class agentgrep.NextAction¶class agentgrep.NextAction¶
Bases:
objectOne engine-authored follow-up action.
-
class agentgrep.RunSummary¶class agentgrep.RunSummary¶
Bases:
objectTerminal engine evidence consumed by every result sink.
-
class agentgrep.SearchResult¶class agentgrep.SearchResult¶
Bases:
objectValidated records plus their engine-owned terminal summary.
-
agentgrep.apply_search_request_patch(query, patch)¶agentgrep.apply_search_request_patch(query, patch)¶
Apply one engine-authored follow-up patch to an existing request.
Targeted conversation caps are request-local: they are retained while targeted effort remains active and cleared when a follow-up escalates to exhaustive effort.
- Parameters:
query (
SearchQuery)patch (
SearchRequestPatch)
- Return type:
Event streams¶
iter_search_events() is the synchronous producer.
aiter_search_events() delivers the same events through a
bounded async queue. A consumer that may stop before SearchFinished must
explicitly close the async generator, for example with
contextlib.aclosing().
-
class agentgrep.events.SearchStarted¶class agentgrep.events.SearchStarted¶
Bases:
_BaseEventEngine resolved its sources and is about to begin scanning.
Emitted exactly once per
agentgrep.iter_search_events()call, immediately afteragentgrep.discover_sources()returns and before the firstSourceStartedevent.
-
class agentgrep.events.SourceStarted¶class agentgrep.events.SourceStarted¶
Bases:
_BaseEventOne source has been picked up and is about to be scanned.
indexis 1-based;totalmatches thesource_countfrom the precedingSearchStartedevent.adapter_iduniquely identifies the source (e.g.codex.sessions_jsonl.v1); the full path is on theSourceFinishedevent’srecords_seen/matches_seentally if a consumer wants per-source detail.
-
class agentgrep.events.RecordEmitted¶class agentgrep.events.RecordEmitted¶
Bases:
_BaseEventA unique, included record. The hot-path event consumers care about.
The embedded
recordis agentgrep’s existingagentgrep.SearchRecorddataclass, not a pydantic copy — consumers (CLI renderer, TUI list) use the record’s attributes directly without a conversion step. Pydantic allows this viaarbitrary_types_allowed=Trueon the model config; the trade-off is thatmodel_dump_json()won’t round-trip these events unmodified, so transport-layer consumers should serialise the record viaagentgrep.mcp.models.SearchRecordModelat the boundary.
-
class agentgrep.events.SourceFinished¶class agentgrep.events.SourceFinished¶
Bases:
_BaseEventOne source finished scanning. Carries per-source counters.
records_seenis every record the adapter parsed from this source;matches_seenis the subset that matched the query (pre-dedup). The dedup decision happens later in the engine, so aRecordEmittedevent may fire for fewer records thanmatches_seenreports.outcomeandstop_reasondistinguish clean completion from a declared bound, unsupported adapter, failure, or cancellation without exposing exception text.
-
class agentgrep.events.SearchFinished¶class agentgrep.events.SearchFinished¶
Bases:
_BaseEventScan complete. Emitted exactly once per stream.
match_countis the total of unique, included records — everyRecordEmittedthat fired earlier counts once. Always the last event in every ordinarily terminalized stream, including source failures represented by the engine summary. Process-levelBaseExceptionvalues still propagate.
-
agentgrep.events.SearchEvent¶agentgrep.events.SearchEvent¶
Discriminated union of every event
agentgrep.iter_search_events()emits.Tagged on the
typeliteral field. Useisinstance(event, RecordEmitted)to narrow inside a loop; pydantic’s discriminator metadata letsty/mypyunderstand the narrowing without extra annotations.alias of
Annotated[SearchStarted|SourceStarted|RecordEmitted|SourceFinished|SearchFinished, FieldInfo(annotation=NoneType, required=True, discriminator=’type’)]
-
class agentgrep.events.FindStarted¶class agentgrep.events.FindStarted¶
Bases:
_BaseEventEngine resolved sources and is about to begin enumerating.
Emitted exactly once per
agentgrep.iter_find_events()call. Unlike search, find has no per-source scan loop, so there is noSourceStarted/SourceFinishedevent pair.
-
class agentgrep.events.FindRecordEmitted¶class agentgrep.events.FindRecordEmitted¶
Bases:
_BaseEventOne discovered source that survived the filter chain.
The embedded
recordisagentgrep.FindRecord. Samearbitrary_types_allowedtrade-off asRecordEmitted: consumers get the dataclass directly; transport-layer consumers convert viaagentgrep.mcp.models.FindRecordModel.
-
class agentgrep.events.FindFinished¶class agentgrep.events.FindFinished¶
Bases:
_BaseEventEnumeration complete.
match_counttotals the emitted records.
-
agentgrep.events.FindEvent¶agentgrep.events.FindEvent¶
Discriminated union of every event
agentgrep.iter_find_events()emits.alias of
Annotated[FindStarted|FindRecordEmitted|FindFinished, FieldInfo(annotation=NoneType, required=True, discriminator=’type’)]
-
agentgrep.iter_search_events(home, query, *, backends=None, control=None, runtime=None, progress=None)¶agentgrep.iter_search_events(home, query, *, backends=None, control=None, runtime=None, progress=None)¶
Yield typed events as the search engine scans sources.
- Parameters:
home (
pathlib.Path) – User home directory passed through toagentgrep.discover_sources().query (
SearchQuery) – Compiled query — terms, agents, dedup choice, limit.backends (
BackendSelection or None) – Override the auto-detected backend selection (mainly used by tests).Noneselects backends viaagentgrep.select_backends().control (
SearchControl or None) – Optional control handle. The generator pollsagentgrep.SearchControl.answer_now_requested()between records so consumers can break the scan early.runtime (
agentgrep.SearchRuntime or None) – Optional reusable runtime state; supplies the source-scan cache when one is configured.progress (
agentgrep.SearchProgress or None) – Optional interactive progress sink. Sinks exposingsummary_finished(summary)receive the same terminal evidence carried byagentgrep.events.SearchFinished.
- Yields:
_events.SearchEvent – Discriminated-union events. See module docstring for the guaranteed sequence.
- Return type:
Iterator[SearchEvent]
Examples
Stream events, collecting matching records:
for event in iter_search_events(pathlib.Path.home(), query): if isinstance(event, _events.RecordEmitted): print(event.record.text)
-
agentgrep.aiter_search_events(home, query, *, backends=None, control=None, runtime=None, max_queue_size=32)¶agentgrep.aiter_search_events(home, query, *, backends=None, control=None, runtime=None, max_queue_size=32)¶
Yield search events from a worker thread through an async queue.
Closing the returned generator — via
contextlib.aclosing(), or by any exception that unwinds through it — requests cancellation and stops the worker. Consumers that may leave the stream partially consumed must close it explicitly rather than relying on the event loop’s async-generator finalization hook.- Parameters:
home (
pathlib.Path) – User home directory passed through toiter_search_events().query (
SearchQuery) – Compiled query — terms, agents, dedupe choice, limit.backends (
BackendSelection or None) – Optional backend override, mostly used by tests.control (
SearchControl or None) – Optional cooperative cancellation handle.runtime (
agentgrep.SearchRuntime or None) – Optional reusable runtime state; supplies the source-scan cache when one is configured.max_queue_size (
int) – Bounded async queue size used to apply consumer backpressure.
- Yields:
_events.SearchEvent – The same event sequence produced by
iter_search_events().- Return type:
AsyncGenerator[SearchEvent]
-
agentgrep.iter_find_events(home, agents, *, pattern, limit, backends=None, compiled=None, type_filter='all')¶agentgrep.iter_find_events(home, agents, *, pattern, limit, backends=None, compiled=None, type_filter='all')¶
Yield typed events as the find engine enumerates sources.
- Parameters:
home (
pathlib.Path) – User home directory passed through toagentgrep.discover_sources().agents (
tuple[AgentName, ...]) – Agent backends to query.pattern (
str or None) – Optional case-insensitive substring filter. WhenNoneevery discovered source qualifies.limit (
int or None) – Optional cap on the number of records emitted.backends (
BackendSelection or None) – Override the auto-detected backend selection (mainly used by tests).Noneselects viaagentgrep.select_backends().compiled (
agentgrep.CompiledQuery or None) – OptionalCompiledQueryfromagentgrep.query.parse_query()+compile_query. When set, itssource_predicateprunes sources before they’re emitted as records. Therecord_predicateis not honored — find emits one record per source by construction, and the per-record query semantics only make sense for the search pipeline.type_filter (
{“prompts”, “history”, “sessions”, “all”}, default “all”) – Coarse source type filter used to prune catalogue roles before discovery. CLI renderers still apply their exact fd-shaped path-kind filter after records are emitted.
- Yields:
_events.FindEvent – Discriminated-union events. See module docstring for the guaranteed sequence.
- Return type:
Iterator[FindEvent]
Examples
Iterate events, collecting only the records:
for event in iter_find_events(home, ("codex",), pattern="sessions", limit=None): if isinstance(event, _events.FindRecordEmitted): print(event.record.path)
Query language helpers¶
Registry-driven query-language documentation.
Single source of truth for the query-language help shown in MCP tool
descriptions, the agentgrep://query-language resource, and the MCP
server instructions. Field docs derive from
agentgrep.query.default_registry() so they cannot drift from what
the compiler actually accepts. Operator docs live here because the
operator grammar is owned by the parser, not the registry.
The CLI --help example blocks deliberately use literal strings (see
agentgrep) rather than this renderer so the root help path stays
cold-start cheap; this module is consumed by the MCP layer, which is not
cold-start sensitive.
-
agentgrep.query.help.query_language_fields(registry=None)¶agentgrep.query.help.query_language_fields(registry=None)¶
Return one
FieldDocper registered field, in registry order.- Parameters:
registry (
FieldRegistry or None) – Registry to render. Defaults todefault_registry().- Returns:
Structured field documentation derived from the registry.
- Return type:
tuple[FieldDoc, ...]
Discovery and search¶
-
agentgrep.select_backends()¶agentgrep.select_backends()¶
Return the best available subprocess helpers.
- Return type:
-
agentgrep.discover_sources(home, agents, backends, *, include_non_default=False, version_detail='shape', store_roles=None, allow_conversation_content_role_fallback=True)¶agentgrep.discover_sources(home, agents, backends, *, include_non_default=False, version_detail='shape', store_roles=None, allow_conversation_content_role_fallback=True)¶
Discover all known parseable sources for the selected agents.
version_detailcontrols how eagerly source handles are enriched:"none"leavesversion_detectionempty for fast search paths,"catalog"attaches low-cost catalog observations, and"shape"inspects concrete source shape for inventory surfaces.store_roleslets latency-sensitive search paths enumerate only the catalogue roles that can satisfy a coarse query scope. Generic callers retain the conversation-content role fallback; search can disable it explicitly when a prompt-only read policy must not enumerate app state.- Parameters:
home (
Path)agents (
tuple[AgentName, ...])backends (
BackendSelection)include_non_default (
bool)version_detail (
DiscoveryVersionDetail)store_roles (
DiscoveryStoreRoles)allow_conversation_content_role_fallback (
bool)
- Return type:
-
agentgrep.run_search_result(home, query, *, backends=None, control=None, runtime=None, progress=None)¶agentgrep.run_search_result(home, query, *, backends=None, control=None, runtime=None, progress=None)¶
Collect one validated event stream into records plus terminal evidence.
- Parameters:
home (
Path)query (
SearchQuery)backends (
BackendSelection|None)control (
SearchControl|None)runtime (
SearchRuntime|None)progress (
SearchProgress|None)
- Return type:
-
agentgrep.run_search_query(home, query, *, backends=None, progress=None, control=None, runtime=None)¶agentgrep.run_search_query(home, query, *, backends=None, progress=None, control=None, runtime=None)¶
Discover sources and run a normalized search query.
- Parameters:
home (
Path)query (
SearchQuery)backends (
BackendSelection|None)progress (
SearchProgress|None)control (
SearchControl|None)runtime (
SearchRuntime|None)
- Return type:
-
agentgrep.search_sources(query, sources, backends, *, progress=None, control=None, runtime=None)¶agentgrep.search_sources(query, sources, backends, *, progress=None, control=None, runtime=None)¶
Parse and filter search results across all selected sources.
- Parameters:
query (
SearchQuery)sources (
list[SourceHandle])backends (
BackendSelection)progress (
SearchProgress|None)control (
SearchControl|None)runtime (
SearchRuntime|None)
- Return type:
-
agentgrep.run_find_query(home, agents, *, pattern, limit, backends=None)¶agentgrep.run_find_query(home, agents, *, pattern, limit, backends=None)¶
Discover sources and build normalized
findresults.- Parameters:
- Return type:
-
agentgrep.find_sources(pattern, sources, limit)¶agentgrep.find_sources(pattern, sources, limit)¶
Build filtered
findresults from discovered sources.- Parameters:
- Return type:
-
agentgrep.discover_listed_sources(home, agents, backends, *, version_detail='shape', store_roles=None)¶agentgrep.discover_listed_sources(home, agents, backends, *, version_detail='shape', store_roles=None)¶
Discover the sources that
findandagentgrep://sourceslist.These are the default-search sources plus the catalog-only stores of the agents in
CATALOG_LISTED_AGENTS, so a listing shows that ChatGPT desktop’s encrypted history exists, with itscoveragesaying search skips it.- Parameters:
home (
pathlib.Path) – Home directory to discover under.agents (
tuple[AgentName, ...]) – Agents to list.backends (
BackendSelection) – Selected external tools.version_detail (
DiscoveryVersionDetail) – How eagerly to enrich source handles; seediscover_sources().store_roles (
DiscoveryStoreRoles) – Roles to list, orNonefor every role.
- Returns:
Listed sources, sorted by agent, store, and path.
- Return type:
Examples
>>> import pathlib, tempfile >>> from agentgrep.discovery import discover_listed_sources >>> from agentgrep.records import BackendSelection >>> home = pathlib.Path(tempfile.mkdtemp()) >>> data = home / "Library/Application Support/com.openai.chat/conversations-v3-x/c.data" >>> _ = data.parent.mkdir(parents=True) >>> _ = data.write_bytes(b"sealed") >>> none = BackendSelection(find_tool=None, grep_tool=None, json_tool=None) >>> [(s.store, s.coverage.value) for s in discover_listed_sources(home, ("chatgpt",), none)] [('chatgpt.conversations', 'catalog_only')]
Stopping discovery¶
A discovery pass on WSL walks the Windows mount, where each stat is a
network round trip. These let a caller end that walk early: the search engine
uses discovery_stop() for a cancelled search, and
the MCP server runs its discovery tools through
discover_in_thread(), so a cancelled request stops
its walk.
-
agentgrep.discovery.discovery_stop(should_stop)¶agentgrep.discovery.discovery_stop(should_stop)¶
Let discovery in this context end early once
should_stop()is true.The search engine abandons a discovery pass when the caller cancels or asks for an answer now, but the abandoned thread would keep walking the filesystem, which on the WSL 9p mount is seconds of round trips. Inside this context, discovery checks the predicate between catalogue rows and roots, ends running file listings, and starts no new
staton the Windows mount, returning the sources found so far. The yieldedDiscoveryStopStatesays whether that happened, so a caller never mistakes a partial result for a complete one. A context variable carries the predicate, soasyncio.to_threadandcontextvars.copy_context()reach worker threads without changing any discover function’s signature.Examples
>>> import pathlib, tempfile >>> from agentgrep.discovery import discover_sources, discovery_stop >>> from agentgrep.records import BackendSelection >>> home = pathlib.Path(tempfile.mkdtemp()) >>> _ = (home / ".claude" / "projects" / "p").mkdir(parents=True) >>> _ = (home / ".claude" / "projects" / "p" / "s.jsonl").write_text("{}") >>> none = BackendSelection(find_tool=None, grep_tool=None, json_tool=None) >>> with discovery_stop(lambda: True) as state: ... print(discover_sources(home, ("claude",), none, include_non_default=True)) [] >>> state.stopped True
- Parameters:
- Return type:
-
class agentgrep.discovery.DiscoveryStopState¶class agentgrep.discovery.DiscoveryStopState¶
Bases:
objectWhether a
discovery_stop()predicate actually cut a pass short.
-
agentgrep.discovery.discover_in_thread(fn, /, *args, **kwargs)¶agentgrep.discovery.discover_in_thread(fn, /, *args, **kwargs)¶
Run blocking discovery in a worker thread that stops when the caller is cancelled.
asyncio.to_thread()cannot stop its thread: cancelling the awaiting task returns at once but leaves the worker walking the filesystem, which on the WSL 9p mount is seconds of round trips while it holds the sharedstatpool. Herefnruns insidediscovery_stop(), and cancelling the awaiting task fires the stop, so the walk ends at its next check and its partial result is dropped with the cancellation.- Parameters:
fn (
Callable) – Blocking work that discovers sources, such asdiscover_sources().*args (
args) – Passed tofn.**kwargs (
kwargs) – Passed tofn.
- Returns:
What
fnreturns when the caller is not cancelled.- Return type:
R
Examples
>>> import asyncio >>> from agentgrep.discovery import discover_in_thread >>> asyncio.run(discover_in_thread(sum, [1, 2, 3])) 6
-
agentgrep.discovery.discovery_without_mtimes()¶agentgrep.discovery.discovery_without_mtimes()¶
Leave each source’s
mtime_nsat 0 inside this context.A listing that neither shows nor filters on a modification time, such as
findwithout anmtime:predicate, has no use for thestatthat reads one, and on the WSL 9p mount thatstatis a round trip per Windows-side file.0already means “unknown” to the query layer.Examples
>>> import pathlib, tempfile >>> from agentgrep.discovery import discover_sources, discovery_without_mtimes >>> from agentgrep.records import BackendSelection >>> home = pathlib.Path(tempfile.mkdtemp()) >>> _ = (home / ".claude" / "projects" / "p").mkdir(parents=True) >>> _ = (home / ".claude" / "projects" / "p" / "s.jsonl").write_text("{}") >>> none = BackendSelection(find_tool=None, grep_tool=None, json_tool=None) >>> with discovery_without_mtimes(): ... [s.mtime_ns for s in discover_sources(home, ("claude",), none)] [0] >>> [s.mtime_ns > 0 for s in discover_sources(home, ("claude",), none)] [True]
Store catalog¶
-
agentgrep.stores.AgentName¶agentgrep.stores.AgentName¶
alias of
Literal[‘claude’, ‘cursor-cli’, ‘cursor-ide’, ‘codex’, ‘gemini’, ‘antigravity-cli’, ‘antigravity-ide’, ‘grok’, ‘pi’, ‘opencode’, ‘windsurf’, ‘chatgpt’, ‘vscode’]
-
agentgrep.stores.PathKind¶agentgrep.stores.PathKind¶
alias of
Literal[‘history_file’, ‘session_file’, ‘sqlite_db’, ‘store_file’]
-
agentgrep.stores.SourceKind¶agentgrep.stores.SourceKind¶
alias of
Literal[‘json’, ‘jsonl’, ‘sqlite’, ‘text’, ‘opaque’]
-
class agentgrep.stores.StoreFormat¶class agentgrep.stores.StoreFormat¶
Bases:
StrEnumOn-disk encoding of a store’s payload.
-
class agentgrep.stores.StoreRole¶class agentgrep.stores.StoreRole¶
Bases:
StrEnumSemantic role a store plays for the owning agent.
Role narrows eligible stores by effort and scope. Fast prompt effort admits prompt-history roles; exhaustive and broad scopes may add chat roles. Coverage separately controls eligibility.
-
class agentgrep.stores.StoreCoverage¶class agentgrep.stores.StoreCoverage¶
Bases:
StrEnumHow agentgrep treats a known store at runtime.
DEFAULT_SEARCHstores are eligible without inventory opt-in; effort and scope still gate their roles.INSPECTABLEstores may join exhaustive or broad-scope search and explicit inventory.CATALOG_ONLYstores are never searched.PRIVATEstores are not enumerated.
-
class agentgrep.stores.VersionDetectionStrategy¶class agentgrep.stores.VersionDetectionStrategy¶
Bases:
StrEnumHow agentgrep detected a concrete source’s app or data version.
-
class agentgrep.stores.VersionDetectionConfidence¶class agentgrep.stores.VersionDetectionConfidence¶
Bases:
StrEnumConfidence level for a detected source version.
-
class agentgrep.stores.DiscoverySpec¶class agentgrep.stores.DiscoverySpec¶
Bases:
BaseModelRuntime metadata for discovering one store’s source files.
Catalogue rows whose store agentgrep actually scans at runtime carry a
DiscoverySpec. Rows that are documentary (planned support, opaque formats, source trees) leaveStoreDescriptor.discoveryasNone.Path resolution¶
The discover function for an agent resolves a base directory (typically
${HOME}/.<agent>or an env-override). Thehome_subpathsegments are appended to that base. Two enumeration modes are then available, used independently or together:fileslists specific relative filenames to check viais_file().globis a pattern walked under the resolved root viaagentgrep.list_files_matching().path_parts_requiredandpath_parts_excludedfilter glob results by path components (e.g., Cursor CLI transcripts must live underagent-transcriptsbut the primary transcript store excludes nestedsubagentsfiles).
platform_pathslists absolute paths to check unconditionally, for stores whose canonical location depends on the operating system.-
model_config: ClassVar[ConfigDict] = {'frozen': True}¶model_config: ClassVar[ConfigDict] = {'frozen': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Runtime store key (e.g.
"claude.projects").
Runtime adapter identifier (e.g.
"claude.projects_jsonl.v1").
Known data-shape version for this discovery path, when stable.
Path segments appended to the agent’s resolved base directory.
Absolute paths to check unconditionally.
Named discovery root to resolve this spec against.
Specific relative filenames to check via
is_file().
Glob pattern walked under the resolved root.
Each named segment must appear in a glob result’s
path.parts.
A glob result is skipped when any named segment appears in
path.parts.
-
class agentgrep.stores.StoreDescriptor¶class agentgrep.stores.StoreDescriptor¶
Bases:
BaseModelOne on-disk storage location for one CLI agent.
Each descriptor is a snapshot of how the store looked when an agentgrep contributor observed it. The
observed_versionandobserved_atfields stamp that snapshot so future readers know whether a description is current or stale.Path patterns use
${HOME}and${<ENV>}tokens so the catalogue stays portable. Resolving a pattern against a concrete environment is the consumer’s job — adapters typically expand the tokens themselves.
-
class agentgrep.stores.StoreCatalog¶class agentgrep.stores.StoreCatalog¶
Bases:
BaseModelVersioned registry of every store agentgrep knows about.
-
agentgrep.store_catalog.gemini_project_hash(project_root)¶agentgrep.store_catalog.gemini_project_hash(project_root)¶
Reproduce Gemini CLI’s project-hash derivation.
Mirrors the
getProjectHashhelper atpackages/core/src/utils/paths.ts:187-189ingithub.com/google-gemini/gemini-cli(HEAD927170fc):export function getProjectHash(projectRoot: string): string { return crypto.createHash('sha256').update(projectRoot).digest('hex'); }
- Parameters:
project_root (
pathlib.Path) – Absolute project root path.- Returns:
Lower-case hex SHA-256 of the absolute path string.
- Return type:
Examples
>>> gemini_project_hash(pathlib.Path("/example")) '99d0533064c83d0483dc07145a0aa887cb104311dac8cc2ca57843c6723a5b69'
Windows host paths (WSL)¶
agentgrep.wsl locates the Windows-side stores from inside a WSL
distro; Windows and WSL describes what discovery does with it.
Windows-host paths as seen from inside a WSL distro.
A WSL distro sees the Windows drives through DrvFs mounts, /mnt/c by
default. Agents installed on the Windows side keep their history under the
Windows profile, so from WSL a Claude desktop session lives at a path such as
/mnt/c/Users/<name>/AppData/Roaming/Claude/.... This module gives those
locations a type, finds the profiles to look in, and prints them without the
Windows account name.
WSLHostPath is a pathlib.PosixPath. Its str() and
os.fspath() are the real path, so it opens, stats, compares, and hashes
like any other path. Only WSLHostPath.display and repr() hide the
account name, by rewriting the profile prefix to a Windows variable.
Three role objects name the places agent stores live:
WSLHost: a mounted Windows drive, such as/mnt/c.WSLHostUserProfile: one%USERPROFILE%.WSLHostAppData:%APPDATA%(AppData/Roaming) or%LOCALAPPDATA%(AppData/Local).
They implement os.PathLike, so they pass anywhere a path does, and
joining one with / returns a WSLHostPath.
Contents, in file order: detection (is_wsl(), mount_root(),
users_root()), profiles (host_user_profiles(),
known_profile_names()), display and its inverse
(display_host_path(), host_display_candidates(),
host_profile_key(), is_host_path()), the path type, and the role
objects.
Examples
Point the users root at a scratch tree, the way AGENTGREP_WSL_USERS_ROOT
does on a real machine:
>>> import os, pathlib, tempfile
>>> from unittest import mock
>>> from agentgrep.wsl import USERS_ROOT_ENV, host_user_profiles
>>> scratch = pathlib.Path(tempfile.mkdtemp()) / "Users"
>>> _ = (scratch / "someone" / "AppData" / "Roaming").mkdir(parents=True)
>>> _ = (scratch / "Public").mkdir()
>>> with mock.patch.dict(os.environ, {USERS_ROOT_ENV: str(scratch)}):
... profiles = host_user_profiles(require_wsl=False)
... claude = profiles[0].appdata / "Claude"
... print(profiles, repr(claude))
(WSLHostUserProfile('%USERPROFILE%'),) WSLHostPath('%APPDATA%/Claude')
>>> str(claude) == str(scratch / "someone" / "AppData" / "Roaming" / "Claude")
True
-
class agentgrep.wsl.WSLHostPath¶class agentgrep.wsl.WSLHostPath¶
Bases:
PosixPathA path on the Windows host, seen from inside WSL.
Behaves exactly like
pathlib.PosixPath:str(),os.fspath(), equality, and hashing all use the real path. The account name is hidden only bydisplayandrepr().Examples
>>> import os, pathlib >>> from unittest import mock >>> from agentgrep.wsl import USERS_ROOT_ENV, WSLHostPath >>> path = WSLHostPath("/mnt/c/Users/someone/.codex/sessions") >>> with mock.patch.dict(os.environ, {USERS_ROOT_ENV: "/mnt/c/Users"}): ... print(repr(path)) WSLHostPath('%USERPROFILE%/.codex/sessions') >>> str(path) '/mnt/c/Users/someone/.codex/sessions' >>> path == pathlib.Path("/mnt/c/Users/someone/.codex/sessions") True >>> hash(path) == hash(pathlib.Path("/mnt/c/Users/someone/.codex/sessions")) True
-
class agentgrep.wsl.WSLHost¶class agentgrep.wsl.WSLHost¶
Bases:
_HostLocationA Windows drive mounted into WSL, such as
/mnt/c.Examples
>>> import pathlib >>> from agentgrep.wsl import WSLHost >>> host = WSLHost.from_drive("C:", pathlib.PurePosixPath("/mnt")) >>> host.drive 'C:' >>> str(host.users) '/mnt/c/Users'
-
class agentgrep.wsl.WSLHostUserProfile¶class agentgrep.wsl.WSLHostUserProfile¶
Bases:
_HostLocationOne Windows user profile,
%USERPROFILE%.Examples
>>> import os >>> from unittest import mock >>> from agentgrep.wsl import USERS_ROOT_ENV, WSLHostPath, WSLHostUserProfile >>> profile = WSLHostUserProfile(WSLHostPath("/mnt/c/Users/someone")) >>> with mock.patch.dict(os.environ, {USERS_ROOT_ENV: "/mnt/c/Users"}): ... print(repr(profile.appdata)) ... print(repr(profile.package_appdata("Vendor.App_abc123") / "App")) WSLHostAppData('%APPDATA%') WSLHostPath('%LOCALAPPDATA%/Packages/Vendor.App_abc123/LocalCache/Roaming/App')
-
class agentgrep.wsl.WSLHostAppData¶class agentgrep.wsl.WSLHostAppData¶
Bases:
_HostLocation%APPDATA%or%LOCALAPPDATA%of one Windows profile.
-
agentgrep.wsl.host_user_profiles(root=None, *, require_wsl=True, should_stop=None)¶agentgrep.wsl.host_user_profiles(root=None, *, require_wsl=True, should_stop=None)¶
Return the Windows user profiles reachable from this distro.
Skips the profiles Windows creates for itself (
Public,Default,Default User,All Users) and anything that is not a directory. Returns an empty tuple off WSL, when the users directory is missing, or when listing it fails, so callers can probe unconditionally.- Parameters:
root (
str|os.PathLike[str] |None) – Users directory to list. Defaults tousers_root().require_wsl (
bool) – Return nothing unlessis_wsl()is true. Tests and explicit callers passFalsetogether with aroot.should_stop (
Callable[[],bool] |None) – Checked before each entry’sis_dirround trip; once it returns true the listing ends with the profiles found so far. Discovery passes its stop check here so an abandoned search stops listing the mount.
- Returns:
Profiles sorted by directory name.
- Return type:
tuple[WSLHostUserProfile, ...]
Examples
>>> from agentgrep.wsl import host_user_profiles >>> host_user_profiles("/nonexistent/Users", require_wsl=False) ()
-
agentgrep.wsl.display_host_path(path)¶agentgrep.wsl.display_host_path(path)¶
Rewrite a path inside a Windows profile to its Windows-variable form.
The profile prefix becomes
%APPDATA%forAppData/Roaming,%LOCALAPPDATA%forAppData/Local, and%USERPROFILE%for the rest of the profile. The account name inside an encoded project folder (C--Users-<name>-work) becomes%USERNAME%, so the Windows account name never reaches output. Every form of a profile path is rewritten: the WSL mount form underusers_root()or under any drive of the automount root (/mnt/d/Users/<name>), and the drive form (C:\Users\<name>) that agents running on Windows record as a working directory. Both print with/, so a printed path pastes into a query unchanged. The match is a string test; it touches no files.- Parameters:
path (
str|os.PathLike[str]) – Absolute path to rewrite.- Returns:
The rewritten path, or
Nonewhenpathis not inside a user profile (paths underPublicand the other service profiles carry no account name and stay as they are).- Return type:
Examples
>>> import os >>> from unittest import mock >>> from agentgrep.wsl import USERS_ROOT_ENV, display_host_path >>> env = mock.patch.dict(os.environ, {USERS_ROOT_ENV: "/mnt/c/Users"}) >>> with env: ... for path in ( ... "/mnt/c/Users/someone/AppData/Roaming/Code/User", ... "/mnt/c/Users/someone/AppData/Local/Packages", ... "/mnt/c/Users/someone/.claude/projects", ... "/mnt/c/Users/someone/.claude/projects/C--Users-someone-work/s.jsonl", ... "/mnt/c/Users/Public/Documents", ... "/home/someone/.claude", ... "C:\\Users\\Some One\\work", ... "C:/Users/someone/AppData/Roaming/Code", ... "/mnt/d/Users/someone/work", ... ): ... print(display_host_path(path)) %APPDATA%/Code/User %LOCALAPPDATA%/Packages %USERPROFILE%/.claude/projects %USERPROFILE%/.claude/projects/C--Users-%USERNAME%-work/s.jsonl None None %USERPROFILE%/work %APPDATA%/Code %USERPROFILE%/work
-
agentgrep.wsl.users_root()¶agentgrep.wsl.users_root()¶
Return the Windows users directory as seen from WSL.
AGENTGREP_WSL_USERS_ROOTwins when set; otherwise the directory is<automount root>/c/Users.- Returns:
The users directory. It may not exist.
- Return type:
-
agentgrep.wsl.mount_root(wsl_conf=_WSL_CONF)¶agentgrep.wsl.mount_root(wsl_conf=_WSL_CONF)¶
Return the directory WSL mounts Windows drives under.
Reads
rootfrom the[automount]section of/etc/wsl.confand falls back to/mntwhen the file, section, or key is missing or unreadable. WSL applies the setting when the distro starts, so the file is read once per process.- Parameters:
wsl_conf (
pathlib.Path) – Distro configuration file to read.- Returns:
Mount root without a trailing slash, such as
/mnt.- Return type:
Examples
>>> import pathlib >>> from agentgrep.wsl import mount_root >>> mount_root(pathlib.Path("/nonexistent/wsl.conf")) PurePosixPath('/mnt')
-
agentgrep.wsl.is_wsl(proc_version=_PROC_VERSION)¶agentgrep.wsl.is_wsl(proc_version=_PROC_VERSION)¶
Return whether this process runs inside a WSL distro.
WSL kernels report
microsoftin/proc/version. Any read error, including a missing file on macOS, means “not WSL”.- Parameters:
proc_version (
pathlib.Path) – Kernel version file to read.- Returns:
Trueon a WSL kernel.- Return type:
Examples
>>> import pathlib >>> from agentgrep.wsl import is_wsl >>> is_wsl(pathlib.Path("/nonexistent/proc/version")) False