DocsFor agents
AI / Automation Mode
On this page
cass is purpose-built for consumption by AI coding agents—not just as an afterthought, but as a first-class design goal. When you're an AI agent working on a codebase, your own session history and those of other agents become an invaluable knowledge base: solutions to similar problems, context about design decisions, debugging approaches that worked, and institutional memory that would otherwise be lost.
Why Cross-Agent Search Matters#
Imagine you're Claude Code working on a React authentication bug. With cass, you can instantly search across:
- Your own previous sessions where you solved similar auth issues
- Codex sessions where someone debugged OAuth flows
- Cursor conversations about token refresh patterns
- Aider chats about security best practices
This cross-pollination of knowledge across different AI agents is transformative. Each agent has different strengths, different context windows, and encounters different problems. cass unifies all this collective intelligence into a single, searchable index.
Self-Documenting API#
cass teaches agents how to use it—no external documentation required:
# First-stop capability contract for agents
cass triage --json
cass capabilities --json
# → {"version": "...", "workflows": [...], "mistake_recoveries": [...], "commands": [...], "exit_codes": [...], "env_vars": [...]}
# Full API schema with argument types, defaults, and response shapes
cass introspect --json
# Topic-based help optimized for LLM consumption
cass robot-docs commands # All commands and flags
cass robot-docs schemas # Response JSON schemas
cass robot-docs examples # Copy-paste invocations
cass robot-docs exit-codes # Error handling guide
cass robot-docs guide # Quick-start walkthrough
Forgiving Syntax (Agent-Friendly Parsing)#
AI agents sometimes make syntax mistakes. cass aggressively normalizes input to maximize acceptance when intent is clear:
| What you type | What cass understands |
Correction note |
|---|---|---|
cass |
cass |
Single-dash long flags normalized |
cass |
cass |
Case normalized |
cass search "auth" |
cass search "auth" |
Snake-case long flag normalized before alias recovery |
cass find "auth" |
cass search "auth" |
find/query/q → search via alias table |
cass |
cass |
Flag-as-subcommand detected |
cass commands |
cass |
Robot-docs topic shorthand detected |
cass schemas |
cass |
Robot-docs topic shorthand detected |
cass ready |
cass triage |
One-shot triage alias |
cass preflight |
cass triage |
One-shot triage alias |
cass |
cass triage |
Top-level robot request defaults to safe preflight |
cass |
cass triage |
Top-level robot request defaults to safe preflight |
cass |
cass search "auth" |
Leading structured flag moved to the robot-capable subcommand |
cass |
cass status |
Leading robot flag canonicalized to JSON output |
cass answer "auth" |
cass pack "auth" |
Cited-handoff aliases normalized to answer pack |
cass why auth failed |
cass pack "auth failed" |
Question/RC prompt aliases normalized to answer pack |
cass auth failed |
cass pack "auth failed" |
Bare robot queries with pack-only flags become answer packs |
cass search auth failed |
cass pack "auth failed" |
Explicit robot search with pack-only flags becomes an answer pack |
cass |
cass |
Reversed HTML export aliases normalized to the archive exporter |
cass current |
cass sessions |
Current-session shorthand normalized to session discovery |
cass sessions current |
cass sessions |
Positional current accepted as the sessions current flag |
cass search |
cass search "auth" |
Named query option converted to required positional query |
cass search |
cass search "auth" |
Short/familiar query aliases converted to required positional query |
cass search auth error |
cass search "auth error" |
Adjacent unquoted query words folded into one search |
cass auth error |
cass search "auth error" |
Unquoted robot-mode query words folded into search |
cass search |
cass search "auth error" |
Query moved before leading search filters |
cass view |
cass view session.jsonl |
Named path option converted to required positional path |
cass view session.jsonl |
cass view session.jsonl |
Legacy alias for ; still reads raw file line 42 |
cass view session.jsonl line_number=42 |
cass view session.jsonl |
A pasted search-hit field selects canonical message 42, not raw line 42 |
cass view source_path=session.jsonl source_id=local line_number=42 |
cass view session.jsonl |
Search hit field bundle accepted as a follow-up command (add conversation_id when the file holds several conversations) |
cass search "auth" |
cass search "auth" |
Familiar format spelling converted to robot format |
cass search "auth" |
cass search "auth" |
Familiar output spelling converted to robot format |
cass help search |
cass |
Structured help intent routed to the machine-readable command reference |
cass |
cass status |
Leading format request moved to the target subcommand |
cass search "auth" |
cass search "auth" |
Result-count alias converted to canonical limit |
cass search "auth" |
cass search "auth" |
Familiar short count flag converted to canonical limit |
cass search "auth" |
cass search "auth" |
Familiar time-window aliases converted to canonical filters |
cass search "auth" last=7d before=now |
cass search "auth" |
Bare time-window assignments converted to canonical filters |
cass search "auth" |
cass search "auth" |
Provider/tool/connector aliases converted to canonical agent filter |
cass search "auth" provider=codex |
cass search "auth" |
Bare provider assignment converted to canonical agent filter |
cass search auth provider codex limit 5 |
cass search auth |
Bare filter key/value pairs after a query converted to canonical flags |
cass search |
cass search |
Flag typos within Levenshtein distance ≤2 corrected |
The CLI applies multiple normalization layers:
- Typo correction: when parsing fails, long flag names within Levenshtein distance 2 of a known flag are corrected (e.g.
→--limt ), and a first word within distance 2 of a subcommand is corrected to it (e.g.--limit serach→search). A word that already names a subcommand is never changed, socass statusruns--jsn status.--json forgetandupgradeare reached only by exact spelling. - Case normalization:
,--Robot →--LIMIT ,--robot --limit - Snake-case flag recovery:
,--max_results , and other known snake_case long flags become canonical kebab-case before alias recovery runs--data_dir - Single-dash recovery:
→-robot (common LLM mistake)--robot - Subcommand aliases:
ready/preflight→triage;find/query/q/grep/lookup→search;session→sessions;answer/evidence/bundle/handoff/why/explain/rca//root-cause rootcause/summarize/summarise→pack;/html-export html_export/exporthtml→;export-html ls/list/info/summary→stats;st/state→status;reindex/idx/rebuild→index;show/get/read→view;diagnose/debug/check→diag;caps/cap→capabilities;inspect/intro→introspect;docs//help-robot robotdocs→robot-docs - Robot-docs topic shorthands: non-command topics such as
commands,schemas,examples,, andexit-codes quickstartbecomeinstead of falling through to search; command topics such asrobot-docs <topic>doctorandsourcesuse structured help (cass help doctor,--json cass sources). Bare--help --json cass guideis reserved for the guided-operations planner; usecassfor the robot-docs walkthrough.robot-docs guide - Root robot default:
cass,--json cass, or--robot casswith no subcommand runs read-only--robot-format jsontriage - Leading structured flag recovery:
/--json before a robot-capable subcommand is moved onto that subcommand--robot - Named positional recovery:
/--query /--q /--text for search/pack and--pattern /--path /--source-path /--file for drill-down/export commands become the required positional argument--session - Multi-word query recovery: adjacent unquoted query words after
search/packbecome one query positional - Structured format recovery:
,--format json|jsonl|compact|sessions|toon, and--output json|jsonl|compact|sessions|toonare accepted as--output-format ...on robot-capable commands;--robot-format ...exportand--format ...exportkeep their export meanings--output <file> - Structured help recovery:
help,--json help commands, and--json searchroute to--help --json /robot-docs guide; plainrobot-docs commandsstays native clap help--help - Result-count aliases:
,--max-results ,--num-results ,--results ,--count , and--top-k become-n on commands with result limits--limit - Time-window aliases:
,--last 7,--before nowlast=7d, andbefore=nowbecome canonical/--since filters--until - Provider aliases:
,--provider ,--tool , and matching assignments become canonical--connector filters on search-like commands--agent - Bare option pairs: after at least one search/pack query word,
provider codex,limit 5, andlast 7dbecome canonical filter flags before the remaining words are folded into the query - Pack-intent recovery: a bare robot query or explicit structured-output
searchwith pack-only flags such as,--max-evidence , or--max-sessions becomes--freshness-policy pack, not implicit or explicitsearch - Drill-down line aliases:
,--line-number and--line_number line=42become(a raw file line)--line - Search-hit fields:
line_number=42pasted from a search hit becomes(the canonical message ordinal the hit names), and a--message-index 42source_path=... source_id=... line_number=...bundle becomes the canonical path,and--source form for follow-up--message-index view/expandcommands - Leading-filter query recovery: if a search/pack query comes after leading options, the query is moved back to the required positional slot
- Implicit robot search: unquoted top-level words with an explicit robot/JSON output request become a
searchquery unless they look like a subcommand typo - Current-session shorthand:
current,, andcurrent-session sessions currentbecomesessions--current - Global flag hoisting: Position-independent flag handling
When corrections are applied, cass emits a teaching note to stderr so agents learn the canonical syntax. In robot/JSON mode the same information is emitted as one note: line per correction on stderr (at most two: the normalization note and the typo-recovery note), so stdout stays data-only. Robot-mode notes are printed only when the command succeeds; a failing command's stderr is its single JSON error envelope. The same notes appear in search output under _meta.effective.auto_corrections with .
Structured Output Formats#
Every command supports machine-readable output:
# Pretty-printed JSON (default robot mode)
cass search "error" --robot
# Streaming JSONL: one hit per line. Add --robot-meta to prepend a
# {budget, _meta} header line (elapsed_ms, next_cursor, state, index_freshness).
# The header also appears without --robot-meta when the search timed out
# (budget.timed_out), returned did-you-mean suggestions, --aggregate or --explain.
cass search "error" --robot-format jsonl # hits only
cass search "error" --robot-format jsonl --robot-meta # 1 _meta header + hits
# Compact single-line JSON (minimal bytes)
cass search "error" --robot-format compact
# Include performance metadata
cass search "error" --robot --robot-meta
# → { "hits": [...], "_meta": { "elapsed_ms": 12, "cache_hit": true, "wildcard_fallback": false, "lexical_degrade_reason": null, ... } }
# lexical_degrade_reason is "query_fuel_exhausted" when a hybrid search dropped its
# lexical leg because Quill's query fuel ran out (see CASS_QUILL_QUERY_FUEL_BUDGET)
# What the search actually ran (--robot-meta): check this instead of trusting the flags
cass search "error" --robot --robot-meta --days 7 | jq '._meta.effective'
# → { "command": "search", "query": "error",
# "query_structure": "error", // how the engine groups operands: `a OR b c` -> "a OR (b AND c)"
# "query_recoveries": [], // e.g. "1 unclosed '(' closed at the end of the query"
# "db_path": "/home/you/.local/share/coding-agent-search/agent_search.db",
# "db_path_source": "default", // --db | env:CASS_DB_PATH | --data-dir | env:CASS_DATA_DIR | env:XDG_DATA_HOME | default
# "time_window": { "since_ms": 1758067200000, "since_from": "--days 7", "until_ms": null, "until_from": null },
# "filters": { "agents": [], "workspaces": [], "source": "all", "sessions_from_paths": null },
# "auto_corrections": [] } // each argv correction, worded like its stderr note
# `cass pack "error" --json` carries the same object for the search it ran in
# its own `_meta.effective` ("command": "pack", and no search-only "daemon"),
# with home-directory paths, private hosts and secrets redacted like the rest
# of the pack (the db_path above reads "[REDACTED_PATH]/agent_search.db").
# Per-hit trust verdict (advisory; --robot-meta only)
cass search "error" --robot --robot-meta
# Each hit then carries a metadata-only `trust` block:
# "trust": {
# "schema_version": 1,
# "trust_tier": "unverified", // trusted | likely | unverified | stale | failed
# "confidence": "medium", // low | medium | high
# "provenance_refs": [], // e.g. ["commit:ab0d12ef90ab", "bead:xyz", "release:v0.6.15"]
# "stale_reason": "aged_out", // present only when not fully trusted
# "recommended_followup": "..." // advisory next step (never a destructive command)
# }
How agents should branch on trust_tier (relevance is not correctness — a
hit can be a landed fix or a failed attempt):
trust_tier |
Meaning | What to do |
|---|---|---|
trusted |
Landed and backed by claim-specific proof (schema-defined in trust_scoring; live search/pack correlation retains proof_debt -> likely until claim-specific proof is supplied) |
Safe to reuse |
likely |
Has provenance (commit/closed bead/release) with proof_debt (not claim-proof-pinned) |
Confirm via the cited ref first |
unverified |
Relevant but no provenance link, or lexical-only corroboration | Corroborate before reuse |
stale |
Aged out (aged_out in live search; superseded_by_newer is schema-defined when supersession markers are supplied) |
Prefer a newer result |
failed |
A failed/reverted attempt (failed_attempt, schema-defined when explicit failure markers are supplied) |
Do not reuse |
The verdict is advisory metadata only — it never changes result ordering.
It is derived from metadata-only signals (recency, source health, realized
search mode, cwd-relative workspace match, and — opportunistically — linked
commit/bead/release provenance); it carries no raw session text. Live cass search
and cass pack correlation currently emits likely, unverified, and stale
(with stale_reason values aged_out, source_unhealthy, workspace_mismatch,
proof_debt, lexical_only, or corroboration_needed), while trusted and
failed remain in the schema v1 TrustTier vocabulary for explicit proof or
failure inputs. The same trust block is attached to cass pack evidence.
Branch on trust_tier and stale_reason, not on confidence alone.
Provenance correlation is project-scoped and explicit-reference anchored:
for a hit from the project you are running cass in now, cass links it to a
closed bead or commit only when the hit's own indexed text references a known
identifier (bead:<id> or commit:<sha>), joined against that project's local
beads and git history. A linked commit's containing release is resolved from
Git. Release containment preserves provenance but does not establish proof of
the excerpt's claim: a landed commit remains proof_debt and cannot become
trusted from this correlation alone. A temporal or
workspace coincidence is never enough, so an unrelated conversation never
inherits another's trust. Off-project hits report workspace_mismatch, and a
hit whose local source file no longer exists on disk reports source_unhealthy
(archive-only) instead of overtrusting a dead path.
# Deterministic answer pack for handoff prompts
cass pack "why did checkout fail" --robot --max-tokens 12000 --limit 40
# Freshness-sensitive pack: fail if selected evidence is outside the window
cass pack "checkout timeout after redirect" --robot \
--freshness-policy strict --freshness-window-seconds 604800 \
--max-tokens 12000 --require-evidence
# Token-budgeted pack for pasting into another agent
cass pack "checkout timeout after redirect" --robot \
--max-tokens 4000 --max-evidence 8 --max-sessions 3 --max-excerpt-chars 600
# Pipeline from broad search to a bounded cited handoff
cass search "checkout timeout" --robot-format sessions \
| cass pack "checkout timeout root cause" --robot --sessions-from -
Design principle: stdout contains only parseable JSON data; all diagnostics, warnings, and progress go to stderr.
Use search when you are still exploring candidate sessions. Use pack when
you need a compact, cited, extractive artifact to hand to another agent or a
human operator. Use status/health before trusting freshness-sensitive output,
and use doctor only for diagnostics or safe repair workflows. Use
when you need a full browsable session archive; packs are
token-budgeted evidence bundles, not full exports and not external
summarization.
When the top hit is a decision question, pack checks for an explicit, on-topic
decision immediately following that question. It also checks sessions containing
the identical question. The question's own answer takes precedence. When other
sessions give conflicting answers, their replies do not displace the question.
A qualifying reply keeps its original citation. This works with
and recognizes English decision language.
For up to 32 retrieved messages, pack can read the immediately following
canonical message even when a quoted query matched only the question. It verifies
the original message and conversation, keeps every search filter, and excludes
context bodies larger than 128 KiB. These additional candidates do not displace
the original retrieval slots or compete as ordinary search hits: only a qualifying
decision reply can be selected, with citation match_type: "answer_context".
If this optional archive read fails, the pack keeps its ranked search evidence and
reports answer_context_unavailable; privacy refusals still stop output.
Pack robot output includes health, freshness, privacy, and warnings.
Warnings such as privacy_redactions_applied, semantic_fallback_lexical,
or no_evidence_found are data, not prose; branch on the JSON fields before
copying the pack into another tool. Stale selected evidence is structural:
inspect freshness.stale_evidence_count.
Packs exclude injected skill payloads by default. Add
to include them explicitly; credential redaction still applies.
privacy.skill_content_included reports whether the selected evidence includes
skill payloads, including after token-budget trimming.
Swarm Operations Workflow#
Use the swarm surfaces when multiple agents are sharing one repo and you need a single read-only view before claiming work:
# Current shared-work snapshot; does not claim, reopen, release, or run builds
cass swarm status --json
# Advisory packet for one bead; still create real reservations and Beads updates yourself
cass swarm work-packet --json --bead coding_agent_session_search-example
# Coordination hygiene check before closeout or takeover review
cass swarm lint --json --bead coding_agent_session_search-example
# Read-only sibling dependency drift sentinel
cass swarm dependency-drift --json
swarm status, swarm , swarm lint, swarm evidence,
swarm and swarm collect the same bounded
read-only Git state and Beads exports when run from the repository root
without a fixture. Git uses
porcelain-v2 with optional locks disabled. Beads uses br (0.6.x or 0.7.x), so its
JSONL snapshot is explicitly partial: unexported database changes may exist.
Recheck Beads and reservations before claiming work. Child commands share a
single 15-second request budget and each has an 8 MiB output cap; Beads categories
cap at 512 issues.
Failures report unavailable providers and unknown summary counts, not zero work.
RCH contributes aggregate active/queued job counts, fleet slots and posture from
rch status (API 1.0, schema 1.0.0). Responses older than 60 seconds or
more than 5 seconds in the future are unavailable. Worker addresses, commands
and job details are omitted. This provider remains partial: local Cargo/CPU
state and build admission are unknown, even when RCH reports no active jobs.
Agent Mail roster and reservation reads are opt-in: set CASS_SWARM_AGENT_MAIL_URL
to the server's HTTP MCP endpoint and, if required, CASS_SWARM_AGENT_MAIL_TOKEN.
The reader uses only resources/read, never a local database fallback or inbox
read. Mail shares the total request budget with a 3-second cap of its own;
responses are capped at 8 MiB, rosters at 512 agents, and full 250-row reservation
pages are refused. The total reservation count remains unknown; source metadata
reports only the observed active count. Activity and expiry use
the observation time. Task descriptions, reservation reasons and message bodies
are omitted. These observations do not authorize claims or establish proof.
CASS evidence remains unwired. Live lint marks itself partial and adds an
advisory whenever Agent Mail messages are not
collected. Fixture selection ( or ) retains deterministic behavior; swarm
also has a live path.
swarm status composes Beads, Agent Mail metadata, git state, rch/build
pressure, cass health/status, and proof references. Stale candidates are
advisory only: coordinate through Beads and Agent Mail before reopening,
force-releasing, or taking over work. Suggested commands are robot-safe
templates, not automatic actions.
The TUI's Swarm tab shows the same live payload for the directory the TUI was
started in. Open it from the command palette (Ctrl+P, "Swarm operations
cockpit") or by clicking its tab; it has no direct key. Entering the tab
starts one background read with this collector;
until it lands, every count shows as ?. Counts of providers that could not
be read stay ?, never zero. r reads again. Rendering never runs a provider
read.
swarm reads Cargo.toml and optional sibling checkouts to
report manifest pins, local HEAD/dirty state, strict validation commands, and
release-risk recommendations. It does not fetch remotes, edit manifests, run
builds, update Beads, send Agent Mail, delete files, or mutate git state.
When status points at prior evidence, use cass pack "query" to create
a bounded cited handoff for another agent. Packs complement the cockpit; they do
not replace Beads for ownership, Agent Mail for coordination, or rch for proof
commands.
Token Budget Management#
LLMs have context limits. cass provides multiple levers to control output size:
| Flag | Effect |
|---|---|
|
Only source_path, line_number, agent, source_id, conversation_id |
|
minimal plus title, score |
|
Custom field selection |
|
Truncate long fields (UTF-8 safe, adds "...") |
|
Soft budget (~4 chars/token); adjusts truncation dynamically |
|
Cap number of results |
cass pack "query" |
Build a cited handoff pack from selected search evidence |
pack |
Set the pack planner's soft budget |
pack |
Cap evidence items selected into the pack |
pack |
Limit how many sessions can contribute evidence |
pack |
Shorten each cited excerpt before token estimation |
pack |
Return top-level summary fields for a smaller JSON envelope |
pack |
Select a documented pack projection; accepts the same presets |
pack |
Reject stale evidence instead of silently mixing it into a pack |
pack |
Restrict pack evidence to newline-delimited session paths; use for stdin |
Truncated fields include a *_truncated: true indicator so agents know when they're seeing partial content.
Contributor verification for docs or contract changes should use rch, for example:
rch exec -- env CARGO_TARGET_DIR=${TMPDIR:-/tmp}/rch_target_cass_answer_pack_docs \
cargo test --test golden_robot_docs
Error Handling for Agents#
Errors are structured, actionable, and include recovery hints. A real sample from cass search foo against a fresh data dir:
{
"error": {
"code": 3,
"kind": "missing-index",
"message": "cass has not been initialized in <data_dir> yet, so search cannot run until the first index completes.",
"hint": "Run 'cass index --full' once to discover local sessions and build the initial archive.",
"retryable": true
}
}
Kind names are kebab-case (e.g. , , , , , timeout, config, ). Agents that branch on err.kind should treat them as stable identifiers. The full set (about 90 kinds) is defined in src/model/cli_error_kind.rs; the canonical way to discover a kind programmatically is to trigger the condition and inspect err.kind from the JSON envelope.
Exit codes follow a semantic convention:
| Code | Meaning | Typical action |
|---|---|---|
| 0 | Success | Parse stdout |
| 1 | Health check failed | Run cass index |
| 2 | Usage error | Fix syntax (hint provided) |
| 3 | Index/DB missing | Run cass index (retryable: true) |
| 4 | I/O failure or unsafe operation refused (not a network code) | Branch on err.kind: fix path/permissions/space for io/; follow the hint for |
| 5 | Data corruption, or maintenance required | Inspect cass health / cass status / cass doctor and follow recommended_action: usually rebuild derived assets (, checkpoint_incomplete start that rebuild themselves); only a canonical-archive failure needs repair or restore |
| 6 | Required input missing (password, resume command) | Supply the input (e.g. ) and rerun |
| 7 | Lock/busy | Retry later |
| 8 | Partial result (sources sync only: some sources had path failures) |
Inspect per-path errors in the JSON output and retry the failed sources |
| 9 | Unknown error | Check retryable flag |
| 10 | Config / timeout | Depends on err.kind |
| 11 | Config validation | Fix config |
| 12 | Source / SSH | Check remote host |
| 13 | Mapping / not-found | Depends on err.kind |
| 14 | I/O / mapping | Retry or inspect path |
| 15 | Semantic / embedder unavailable | Install model or |
| 20-21 | Model acquisition | Check err.kind, err.hint |
| 22 | I/O during model handling | Retry |
| 23 | Model download | Retry or use |
| 24 | I/O during model verify/install | Retry |
| 70 | cass index stalled and aborted (kind envelope on stderr) |
Inspect cass status , then rerun cass index |
| 130 | Interrupted (SIGINT) | Rerun; cass sources setup continues an interrupted setup |
Structured search/pack timeouts are not exit 8: on expiry search and pack exit 0 with {"hits": [], "budget": {"timed_out": true, "skipped_sections": [...], "recommended_next_probe": "<command>", ...}}, and instead fails with exit 10, kind timeout. Human-readable search and Markdown pack return exit 10 with timeout guidance and no result output when their configured deadline expires. Explicit also fails with exit 10, kind timeout, retryable: true, and a semantic_budget checkpoint=... message when the remaining budget cannot admit semantic setup or dispatch, rather than returning an empty or lexical result. Hybrid (explicit or default) instead falls back to lexical and reports semantic_budget_limited.
Codes ≥ 10 are domain-specific and the numeric value alone is ambiguous (e.g. code 10 maps to either config or timeout kinds depending on context). Agents should branch on err.kind from the JSON error envelope — not on the numeric code — when handling codes ≥ 10. See the Error Handling section above for the canonical kind list.
The retryable field tells agents whether a retry might succeed (e.g., transient I/O) vs. guaranteed failure (e.g., invalid path). A lexical query the engine refuses with posting cursor invariant failed (kind search, exit 9) is retryable: false: the same query fails the same way on the same index generation. The hint names the remedy, cass index . Date-filtered searches over an index segment that holds deleted rows triggered it before frankensearch-quill 0.3.2 (GH #499).
Session Analysis Commands#
Beyond search, cass provides commands for deep-diving into specific sessions:
# Discover the current session for this workspace
cass sessions --current --json
# List recent sessions for a specific project
cass sessions --workspace /path/to/project --json --limit 5
# Export full conversation to shareable format
cass export /path/to/session.jsonl --format markdown -o conversation.md
cass export /path/to/session.jsonl --format json --include-tools
# Export just user prompts and assistant replies
cass export /path/to/session.jsonl --messages-only --format json
cass export /path/to/session.jsonl --messages-only -o conversation.md
cass export-html /path/to/session.jsonl --messages-only --json
# Export as self-contained HTML with encryption (recommended for sharing)
cass export-html /path/to/session.jsonl # To Downloads folder
printf '%s\n' "pwd" | cass export-html session.jsonl --encrypt --password-stdin
cass export-html session.jsonl --open --json # Open in browser, JSON output
# Common agent flow: find current session, then export it
cass export-html "$(cass sessions --current --json | jq -r '.sessions[0].path')" --json
# Expand context around a specific line (from search result)
cass expand /path/to/session.jsonl -n 42 -C 5 --json
# → Shows 5 messages before and after line 42
# Activity timeline: when were agents active?
cass timeline --today --json --group-by hour
cass timeline --since 7d --agent claude --json
# → Grouped activity counts, useful for understanding work patterns
is an optional export projection for Markdown, text, JSON and
HTML, including . It keeps user prompts and assistant prose while
omitting system turns, tool calls/results, reasoning blocks and non-text
attachments. Mixed messages retain their text blocks in source order. This
option does not change canonical rows, raw mirrors, source logs or indexing
policy; it also works from an indexed conversation whose source file is gone.
It conflicts with explicit , and
--include-system-reminders. Credential redaction still applies unless
is explicitly requested.
Messages-only JSON uses an envelope with messages and projection. The
projection reports input_records, retained_messages, omitted_records and
canonical_history_preserved: true; these counts describe records, so removing
tool blocks from a retained mixed message does not add an omitted record.
Ordinary JSON exports keep their existing array shape. Every retained message
has its original zero-based source_index; archived messages also have their
one-based canonical message_index for view and
expand . Available source IDs and timestamps are preserved.
HTML JSON receipts, dry runs and explain plans include the same projection
counts, and other formats report them on stderr. A transcript containing only
omitted records produces an empty messages-only export with explicit counts.
Legacy archives sometimes retain only flattened text rather than the original
mixed content blocks. In that case the projection conservatively keeps text
before the first recognized tool or reasoning marker. This also applies to
direct OpenCode SQLite exports, whose connector supplies flattened content.
Direct OpenCode file exports preserve part boundaries and retain prose after
tool or reasoning parts. Retained JSON prefixes
carry content_projection: "legacy-visible-prefix"; prose interleaved after
that marker cannot be reconstructed safely. Explicit text blocks in preserved
source records are kept as written, including ordinary discussion of such
markers. Known Cline SDK archive rows without a preserved source envelope are
omitted because their flattened text has no reliable boundaries between prose,
reasoning, attachments and tool results. The omission count includes these
rows. Export titles are derived from retained prompts so an omitted tool
result cannot reappear in the title or generated filename.
Aggregation & Analytics#
Aggregate search results server-side to get counts and distributions without transferring full result data:
# Count results by agent
cass search "error" --robot --aggregate agent
# → { "aggregations": { "agent": { "buckets": [{"key": "claude_code", "count": 45}, ...] } } }
# Multi-field aggregation
cass search "bug" --robot --aggregate agent,workspace,date
# Combine with filters
cass search "TODO" --agent claude --robot --aggregate workspace
Aggregation Fields:
| Field | Description |
|---|---|
agent |
Group by agent type (claude_code, codex, cursor, etc.) |
workspace |
Group by workspace/project path |
date |
Group by date (YYYY-MM-DD) |
match_type |
Group by match type (exact, prefix, suffix, substring, wildcard, implicit_wildcard); one search has one type, so this shows a single bucket unless the wildcard fallback replaced the hits |
Response Format:
{
"aggregations": {
"agent": {
"buckets": [
{"key": "claude_code", "count": 120},
{"key": "codex", "count": 85}
],
"other_count": 15
}
}
}
Top 10 buckets are returned per field, with other_count for remaining items.
Bounded incident mining#
Mine recurrent CASS operational incidents from the canonical archive without dumping raw session text:
cass analytics incidents --limit 10 --json
# Tighten the bounded scan for automation or a very large archive
cass analytics incidents --max-sessions 500 --max-messages 50000 \
--max-bytes 67108864 --budget-ms 5000 --json
The response ranks top_sessions[] by hit count and category breadth and keeps
the exact conversation_id, agent, host, source_id, source_path,
live/archive state, dominant categories, and a structured cass view argv.
That argv carries the effective path plus , so it
opens the exact ranked archive row even when multiple sessions share a source
path or the report used a non-default database.
total_sessions, total_hits, and top_sessions_truncated distinguish the
bounded ranked result from the totals observed inside the scan scope.
discovery.partial and stop_reason explicitly distinguish a bounded partial
scan from a complete scan. Counts are scoped to scanned candidates whenever the
scan is partial. is a hard wall-clock result guard around the
independently row-bounded read-only worker. If it expires before a verified
result arrives, count_scope="no_verified_results_hard_timeout" returns an
empty partial report instead of overstating in-flight observations. Candidate
discovery is descending archive-row keyset paging;
bounds that newest-row window before dimensional filters, so a
selective filter can truthfully return a partial empty result instead of scanning
an unbounded archive. Individual messages are inspected through a bounded 4,096-char
fragment; an oversized message returns rather than
claiming a complete corpus scan. Raw prompt/tool content is always suppressed; evidence carries
only BLAKE3 fingerprints and basename-redacted paths. The actionable
source_path remains visible solely so the returned view command works.
Chained Search (Pipeline Mode)#
Chain multiple searches together by piping session paths from one search to another:
# Find sessions mentioning "auth", then search within those for "token"
cass search "authentication" --robot-format sessions | \
cass search "refresh token" --sessions-from - --robot
# Build a filtered corpus from today's work
cass search --today --robot-format sessions > today_sessions.txt
cass search "bug fix" --sessions-from today_sessions.txt --robot
How It Works:
- First search with
outputs one session path per line--robot-format sessions - Second search with
restricts search to those sessions--sessions-from <file> - Use
to read from stdin for true piping-
Use Cases:
- Drill-down: Broad search → narrow within results
- Cross-reference: Find sessions with term A, then find term B within them
- Corpus building: Save session lists for repeated searches
Match Highlighting#
Snippets always mark the terms the search engine matched with **bold**, in human-readable output and in robot/JSON output alike. The flag also marks the query terms' remaining literal occurrences and leaves already-marked text alone, so no term gets two pairs of marks. Only the snippet field is marked; content stays verbatim:
cass search "authentication error" --robot --highlight
# "snippet": "... **authentication** failed with **error** ..."
Highlighting is query-aware: quoted phrases like "auth error" highlight as a unit; individual terms highlight separately.
Pagination & Cursors#
For large result sets, use cursor-based pagination:
# First page
cass search "TODO" --robot --robot-meta --limit 20
# → { "hits": [...], "_meta": { "next_cursor": "eyJ..." } }
# Next page
cass search "TODO" --robot --robot-meta --limit 20 --cursor "eyJ..."
A cursor is base64 JSON {"offset": N, "limit": M}: a plain page position, not a snapshot. Any index change between pages (a new session indexed, a rebuild, a forget) shifts the ranking, so the next page can skip or repeat hits. Page quickly, or fix the window with when you need stable pages.
Match Counts: Exact or Lower Bound#
total_matches answers "how many messages match?", but it is exact only when
cass can afford to count. Every search fetches one hit beyond to learn
whether another page exists. When the page is full and the index is larger than
CASS_SEARCH_EXACT_TOTAL_COUNT_MAX_DOCS documents, cass skips the full count
and reports that limit + 1 as a lower bound. Below the threshold it counts
every match.
| Build | Threshold | stale lock with on a 1,034,219-document index |
|---|---|---|
| v0.9.0 and earlier | 50,000 documents | total_matches: 11 |
| v0.10.0 and later | 5,000,000 documents | total_matches: 11915 |
says which kind of number you got:
cass search "stale lock" --robot --robot-meta --limit 10 \
| jq '{total_matches, precision: ._meta.cursor_manifest.count_precision, why: ._meta.cursor_manifest.count_reason}'
# → {"total_matches": 11915, "precision": "exact", "why": "total_matches is exact; no extra recount was needed"}
# A lower bound reads "precision": "lower_bound".
Why the threshold moved. The 50,000 cap dates from the Tantivy engine,
where counting a common term over millions of documents could dominate the
query. The Quill engine counts cheaply. Paired runs on that 1,034,219-document
archive, capped against exact (, read-only, CPU time):
| Query | Exact total | Extra CPU for the exact count |
|---|---|---|
stale lock |
11,915 | ~0.00-0.04 s |
cargo build |
24,944 | ~0.01-0.03 s |
the |
439,461 | ~0.03-0.05 s |
AGENTS.md |
867,087 | ~0.06-0.11 s |
Each search cost about 0.8 s of CPU either way. The capped answer, meanwhile,
was wrong by up to five orders of magnitude, and agents read total_matches as
a count. The default now covers five times that archive; set
CASS_SEARCH_EXACT_TOTAL_COUNT_MAX_DOCS=0 to never count exactly, or raise it
for a larger archive.
Aggregations have their own window. buckets are computed over
the top max(1000, limit + offset) hits, so bucket counts on a large archive
describe the best-ranked thousand matches, not the whole corpus. Use an exact
total_matches for "how many", and aggregations for "how are the top hits
distributed".
Request Correlation#
For debugging and logging, attach a request ID:
cass search "bug" --robot --request-id "req-12345"
# → { "request_id": "req-12345", "hits": [...], ... }
# (top level always; also under _meta.request_id with --robot-meta)
Idempotent Operations#
For safe retries (e.g., in CI pipelines or flaky networks):
cass index --full --idempotency-key "build-$(date +%Y%m%d)"
# If same key + params were used in last 24h, returns cached result
Query Analysis#
Debug why a search returned unexpected results:
cass search "auth*" --robot --explain
# → Adds "explanation": the sanitized query, flat lists of its terms, phrases and
# operators (not a tree), the query type and index strategy, a low/medium/high cost
# class, a filter summary and warnings. Wildcards are reported, not expanded.
cass search "auth error" --robot --dry-run
# → Validates query syntax without executing
Traceability#
For debugging agent pipelines:
cass search "error" --robot --trace-file /tmp/cass-trace.json
# Appends execution span with timing, exit code, and command details
cass index --full --json --robot-trace-ingest 2>/tmp/cass-ingest-trace.jsonl
# Streams one NDJSON record per ingest batch with wall_ms, batch_msgs,
# inserted_messages, and duplicate-lookup counters for perf bisects
Search Flags Reference#
| Flag | Purpose |
|---|---|
/ |
JSON output (pretty-printed) |
|
Streaming or single-line JSON |
|
Include _meta block (elapsed_ms, cache stats, index freshness, lexical_degrade_reason: "query_fuel_exhausted" or null, wildcard_fallback_skipped: why a sparse result got no automatic wildcard retry, and effective: the database, time window, filters, auto-corrections and query grouping the search actually used) |
|
Reduce payload size |
|
Truncate content fields to N chars |
|
Apply an approximate token budget to robot output |
|
Timeout in milliseconds. Structured search/pack emit a partial result with budget.timed_out: true; human search , Markdown pack, and fail with exit 10, kind timeout. 0 disables an explicit timeout |
|
Cursor-based pagination (from _meta.next_cursor) |
|
Echoed in response for correlation |
|
Server-side aggregations |
|
Include query analysis (parsed query, cost estimate) |
|
Validate query without executing |
|
Strict read-only search: never refresh, join, or spawn lexical maintenance, never auto-repair the archive while opening it, and never auto-spawn the daemon (conflicts with and ) |
|
Filter by source: local, remote, all, or specific source ID |
|
Also mark query-term occurrences the engine left unmarked (snippets always mark matched terms with **) |
Index Flags Reference#
| Flag | Purpose |
|---|---|
|
Safe retries: same key + params returns cached result (24h TTL) |
|
JSON output with stats |
|
Reclaim merge-retired lexical segment files and exit: runs the engine's grace-period garbage sweep (a folded segment file is unlinked only once no published MANIFEST generation has referenced it for 300 s) and reports files/bytes reclaimed. Every incremental cass index performs the same sweep at open; doctor reports the reclaimable bytes under storage_pressure.full_rebuild_readiness (GH #453) |
|
Run any lexical rebuild in this invocation as a single-core, low-memory rebuild for a wedged or memory-starved archive: one rebuild worker, one page-prep thread, a one-page pipeline, 64 conversations per fetch and a durable commit every 64 MiB of text (the Lexical Rebuild Tuning recipe below under one name). An explicit CASS_TANTIVY_REBUILD_* value still wins over the preset, and the responsiveness governor can still lower it. reports rebuild_profile: each preset knob with source profile or env, and the effective settings. It never changes what is indexed. Default: default (host-sized) (GH #483) |
When health or status reports index.status: "hollow", the
live Quill generation serves fewer than half the documents certified by its
completed rebuild checkpoint. index.live_documents reports the served count.
Run cass index to let its pre-scan repair rebuild from the canonical archive;
cass index also rescans the session sources. A missing count provides
no hollow-generation verdict.
index.manifest_source (also under search _meta.index_freshness and in cass serve's snapshot) names the MANIFEST
slot readers serve: current,
previous_after_missing_current or previous_after_corrupt_current. A corrupt
current MANIFEST is read through MANIFEST.prev, the generation before the
newest publish, so the index reports stale and health reports it as an
error; cass index rebuilds the generation from the canonical archive.
Recovering an Interrupted Lexical Rebuild#
Rerun cass index after an interrupted
rebuild. A saved scratch generation can retain its committed documents when
new conversations or messages have entered the canonical archive, including
messages appended to conversations it already processed. Recovery streams the
canonical archive again to verify those documents and adds only missing
document identities. Final segment maintenance can still rewrite retained
segments. Verification progress therefore starts at the first conversation;
that does not mean the committed index work was discarded.
Every retained document must match the canonical identity and full projected
content, and every document in the saved generation must be accounted for.
Edits or deletions affecting retained search documents, a replaced archive,
incompatible projection settings, and damaged or inconsistent index evidence
reject reuse. The rejected candidate is retained in a
.lexical-rebuild-quarantine-* directory and a fresh replacement is built
off-live. Explicit still requests a fresh pass: it never
reuses a generation from before it started. If that pass is itself
interrupted, rerunning cass index with the same cass build
continues it, provided the archive has not been written since the pass began.
The rerun reads the archive from the start again but indexes only the
conversations the pass had not committed, or only finishes its final merge.
Any archive write, another cass build, or starts over.
The audit shares the immutable native snapshot admitted by the candidate's writer. It does not independently open an earlier generation and then assume the writer received the same one. Publication retains the fingerprint of the generation verified while that writer was held; a later native generation change returns a retryable failure without transferring the old content proof.
Recovery checkpoints bind the archive's stable file identity, lexical schema, packet contract, and per-message content cap. Older version-three checkpoints that explicitly identify a staged single index can be adopted only through the complete content audit; their old conversation cursor never authorizes skipping rows. They cannot establish historical file identity before that upgrade. Incomplete shared-writer and live-index checkpoints restart off-live, including checkpoints that carry an archive binding.
Completed generations are also bound to their native manifest and the observed canonical DB/WAL write epoch. If that evidence has changed, an explicit rebuild performs a bounded read-only content audit before reusing the live generation. This includes harmless bookkeeping writes: equal row counts alone never renew rebuild authority. A matching audit retains the index without rewriting its documents; a mismatch starts a replacement off-live. Successful verification refreshes the paired generation and equivalence evidence before recording completion, while leaving the native index unchanged.
Search and status distinguish a verified current generation from an
unverified one. Bookkeeping or WAL changes can make source evidence
unverified while the complete native generation remains readable. Reads keep
serving that generation with the verification reason; the label alone does
not start a full content audit or a rebuild loop. Ordinary count drift,
pending replay work, and source-scan scheduling keep their existing refresh
behavior. A confirmed archive-identity or projection-contract mismatch
requires repair. The archive-fingerprint cache cannot renew an older
checkpoint's authority under a newer database identity.
Newly indexed batches are committed and checkpointed durably. A further interruption preserves those batches too. Readers keep the prior published generation until the candidate, its manifest, and its completed receipt are ready for the existing atomic swap. A canonical database write detected during verification or publication returns an error and retains the generation for a verified retry. Any saved completion evidence remains bound to the source epoch that was actually audited. CASS's archive writer lease excludes cooperating canonical writers; external session files can keep growing, and a later indexing scan ingests those files after canonical recovery finishes.
The bounded profile, per-message cap, responsiveness limits, disk headroom checks, and bounded merge planner still apply. The audit does not retain an archive-sized set of message identities. Its source reads and native content checks still cost time, and the existing controls do not guarantee a fixed total-process RSS ceiling. See the recovery design and validation record for the test matrix and measured scope.
Robot Documentation System#
For machine-readable documentation, use cass :
| Topic | Content |
|---|---|
commands |
Full command reference with all flags |
env |
Environment variables and defaults |
paths |
Data directory locations per platform |
guide |
Quick start guide for automation |
schemas |
JSON response schemas |
|
Exit code meanings and retry guidance |
examples |
Copy-paste usage examples |
contracts |
API contract version and stability |
sources |
Remote sources configuration guide |
# Get documentation programmatically
cass robot-docs guide
cass robot-docs schemas
cass robot-docs exit-codes
# Machine-first help (wide output, no TUI assumptions)
cass --robot-help
API Contract & Versioning#
cass maintains a stable API contract for automation:
cass api-version --json
# → { "crate_version": "<cargo version>", "build_commit": "<sha or unknown>", "api_version": 1, "contract_version": "1" }
cass introspect --json
# → Full schema: all commands, arguments, response types
Contract Version: Currently 1. Increments only on breaking changes.
Guaranteed Stable:
- Exit codes and their meanings
- JSON response structure for
output--robot - Flag names and behaviors
_metablock format
Ready-to-paste blurb for AGENTS.md / CLAUDE.md#
🔎 cass — Search All Your Agent History
What: cass indexes conversations from Claude Code, Codex, Cursor, Gemini, Aider, ChatGPT, and more into a unified, searchable index. Before solving a problem from scratch, check if any agent already solved something similar.
⚠️ NEVER run bare cass — it launches an interactive TUI. Always use --robot or --json.
Quick Start
# One-shot agent triage (read next_command when present)
cass triage --json
# Search across all agent histories
cass search "authentication error" --robot --limit 5
# Build a cited handoff pack from search evidence
cass pack "authentication error root cause" --robot --max-tokens 12000 --limit 40
# Tight handoff budget with freshness and privacy metadata
cass pack "authentication error root cause" --robot --max-tokens 4000 --max-evidence 8 --fields summary
# View a specific result (from search output)
cass view /path/to/session.jsonl -n 42 --json
# Expand context around a line
cass expand /path/to/session.jsonl -n 42 -C 3 --json
# Learn the full API
cass capabilities --json # Static agent self-description
cass robot-docs guide # LLM-optimized docs
Why Use It
- Cross-agent knowledge: Find solutions from Codex when using Claude, or vice versa
- Forgiving syntax: Typos and wrong flags are auto-corrected with teaching notes
- Token-efficient: --fields minimal returns only essential data; pack budgets cite only selected evidence
- Copy-safe handoffs: pack warnings include freshness and privacy/redaction status
Key Flags
| Flag | Purpose |
|------------------|--------------------------------------------------------|
| --robot / --json | Machine-readable JSON output (required!) |
| --fields minimal | Reduce payload: source_path, line_number, agent, source_id, conversation_id |
| pack --max-tokens N | Budget a cited handoff pack |
| --limit N | Cap result count |
| --agent NAME | Filter to specific agent (claude, codex, cursor, etc.) |
| --days N | Limit to recent N days |
stdout = data only, stderr = diagnostics. Exit 0 = success.