cass
"Coding Agent Session Search - unified CLI/TUI to index and search local coding agent history from Claude Code, Codex, Gemini, Cursor, Aider, ChatGPT, Pi-Agent, Factory, and more. Purpose-built for AI agent consumption with robot mode."
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/dicklesworthstone/coding_agent_session_search with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/dicklesworthstone/coding_agent_session_search'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/dicklesworthstone-coding-agent-session-search)HTML
<a href="/listings/dicklesworthstone-coding-agent-session-search"><img src="/api/listings/dicklesworthstone-coding-agent-session-search/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
⚠️ **Never run bare `cass` in an agent context** — it launches the interactive TUI. Always use `--robot` or `--json`.
# 1) Check the installed interface once per version (recipe verified on 0.8.0). cass --version cass search --help # Verify a newly installed executable without opening the configured archive. cass selftest --json # `health --binary-only` still reports (and therefore probes) archive readiness. # 2) For a quick history question, start with scoped read-only lexical retrieval. # Hybrid remains the product default; lexical is explicit for this workflow. cass search "performance regression" --workspace /path/to/project --days 7 \ --mode lexical --no-maintenance --robot --robot-meta --fields minimal \ --limit 5 --max-tokens 2000 --timeout 2000 # 3) Find the current or recent session for this workspace cass sessions --current --json cass sessions --workspace "$(pwd)" --json --limit 5 # 4) View + expand a hit (use source_path/line_number from search output) cass view /path/to/session.jsonl -n 42 -C 3 --json --timeout 2000 # 5) Discover the full machine API cass capabilities --json cass robot-docs guide cass robot-docs schemas # 6) Exclude a noisy agent harness from future indexing cass sources agents list --json cass sources agents exclude openclaw cass sources agents include openclaw
The retrieval flags above are available in 0.8.0. On older builds, check help; if `--no-maintenance` is absent, report the mismatch instead of dropping the read-only constraint. `--timeout` is in milliseconds, while `--max-tokens` limits approximate output size. Also set a caller-side deadline (for example, GNU `timeout 10s`); an externally interrupted command may leave incomplete JSON. Inspect `budget.timed_out` even after exit 0: timed-out empty hits are not proof that no history exists. A `maintenance-required` response ends the retrieval attempt; indexing or repair is a separate mutating task. Use triage/health/status for readiness diagnosis, not as repeated prerequisites to a short summary. Broaden scope deliberately, expand useful hits, and preserve source/line citations. `view -C` bounds context lines, not bytes; check excerpt size before including a long JSONL record in an agent prompt.
**Output conventions** - stdout = data only - stderr = diagnostics - exit 0 = success
**Search asset contract** - SQLite is the source of truth for indexed conversations and messages. All derived assets (lexical index, semantic vectors, analytics rollups, retention backups) can be rebuilt from SQLite; no derived asset is authoritative. - Lexical search is the required fast path. Missing, stale, or incompatible lexical assets are treated as derived-state problems that cass should rebuild from SQLite instead of asking operators to perform routine manual repair. - Hybrid is the default search intent. Robot metadata (`--robot --robot-meta`) reports the requested mode, realized mode, semantic refinement status, and any lexical fallback reason when semantic assets are not ready. - Semantic assets are opportunistic background enrichment. Lexical-only results are expected during first indexing, semantic catch-up, disabled semantic policy, or unavailable local model/vector files. - Semantic model acquisition is **opt-in**: `cass models install` downloads the default `all-minilm-l6-v2` (alias `minilm`, ~90 MB) only on explicit request; `--model multilingual-minilm` selects the larger multilingual MiniLM L12 model (~480 MB) for CJK/mixed-language archives. Cass never auto-downloads or auto-selects the multilingual space. Air-gapped installs use `--from-file <dir>`. While the selected model is absent, hybrid search uses lexical-only and reports `fallback_mode="lexical"` in health/status.
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 996 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- ---
- name: cass
- description: "Coding Agent Session Search - unified CLI/TUI to index and search local coding agent history from Claude Code, Codex, Gemini, Cursor, Aider, ChatGPT, Pi-Agent, Factory, and more. Purpose-built for AI agent consumption with robot mode."
- ---
- # CASS - Coding Agent Session Search
- Unified, high-performance CLI/TUI to index and search your local coding agent history. Aggregates sessions from **23 agents**, including Codex, Claude Code, Gemini CLI, Cline, OpenCode, Amp, Cursor, ChatGPT, Aider, Pi-Agent, Factory (Droid), OpenHands, Antigravity, and Grok Build.
- ## CRITICAL: Robot Mode Required for AI Agents
- **NEVER run bare `cass`** - it launches an interactive TUI that blocks your session!
- ```bash
- # WRONG - blocks terminal
- cass
- # CORRECT - JSON output for agents
- cass search "query" --robot
- cass search "query" --json # alias
- ```
- **Always use `--robot` or `--json` flags for machine-readable output.**
- ---
- ## Quick Reference for AI Agents
- ### Bounded History Retrieval
- For a quick project-history question, start with one scoped query. The flag set
- below is verified on cass 0.8.0; check `cass --version` and `cass search --help`
- once per installed version. If `--no-maintenance` is unsupported, stop and report
- the version mismatch; silently removing it permits maintenance.
- ```bash
- # Specific terms, one workspace, recent history, small cited result set
- cass search "performance regression" --workspace /path/to/project --days 7 \
- --mode lexical --no-maintenance --robot --robot-meta --fields minimal \
- --limit 5 --max-tokens 2000 --timeout 2000
- # Expand only a useful hit, using its exact source_path and line_number
- cass view /path/to/session.jsonl -n 42 -C 3 --json --timeout 2000
- ```
- `--timeout` is in milliseconds; `--max-tokens` is an approximate output budget,
- not a CPU or memory limit. Apply a caller-side wall-clock deadline as well (for
- example, GNU `timeout 10s` before the command). Exit 124 from that wrapper is an
- incomplete attempt; its interrupted stdout may not be valid JSON. In JSON search
- output, inspect `budget.timed_out` even after exit 0: empty timed-out hits do not
- prove that no history exists.
- `view -C 3` limits surrounding lines, not bytes or tokens; a single JSONL record
- can be large. Check its output size before adding excerpts to a prompt.
- Hybrid remains the product default. Explicit lexical mode keeps this workflow
- out of semantic inference; `--no-maintenance` prevents index repair, catch-up,
- and daemon auto-spawn. If it returns `maintenance-required`, report that blocker
- and stop this retrieval attempt. Do not turn a summary request into an index,
- repair, model-install, wildcard-aggregate, or repeated health/status workflow.
- Use readiness commands when diagnosing readiness; review their proposed actions
- before starting a separate mutating task. Broaden dates or terms deliberately
- after a completed query; choose semantic/hybrid only when conceptual retrieval
- is needed and its cost is acceptable. Preserve source/line citations in summaries.
- ### Essential Commands
- ```bash
- # Find the current session for this workspace
- cass sessions --current --json
- # List recent sessions for a specific project
- cass sessions --workspace "$(pwd)" --json --limit 5
- # Common agent flow: find current session, then export it
- cass export-html "$(cass sessions --current --json | jq -r '.sessions[0].path')" --json
- # Search with JSON output
- cass search "authentication error" --robot --limit 5
- # Search with metadata (elapsed_ms, cache stats, freshness)
- cass search "error" --robot --robot-meta
- # Minimal payload (path, line, agent only)
- cass search "bug" --robot --fields minimal
- # View source at specific line
- cass view /path/to/session.jsonl -n 42 --json
- # Expand context around a line
- cass expand /path/to/session.jsonl -n 42 -C 5 --json
- # Capabilities discovery
- cass capabilities --json
- # Full API schema
- cass introspect --json
- # LLM-optimized documentation
- cass robot-docs guide
- cass robot-docs commands
- cass robot-docs schemas
- cass robot-docs examples
- cass robot-docs exit-codes
- ```
- ---
- ## Why Use CASS
- ### Cross-Agent Knowledge Transfer
- Your coding agents create scattered knowledge:
- - Claude Code sessions in `~/.claude/projects`
- - Codex sessions in `~/.codex/sessions`
- - Cursor state in SQLite databases
- - Aider history in markdown files
- CASS **unifies all of this** into a single searchable index. When you're stuck on a problem, search across ALL your past agent sessions to find relevant solutions.
- ### Use Cases
- ```bash
- # "I solved this before..."
- cass search "TypeError: Cannot read property" --robot --days 30
- # Cross-agent learning (what has ANY agent said about X?)
- cass search "authentication" --robot --workspace /path/to/project
- # Agent-to-agent handoff
- cass search "database migration" --robot --fields summary
- # Daily review
- cass timeline --today --json
- ```
- ---
- ## Command Reference
- ### Indexing
- ```bash
- # Full rebuild of DB and search index
- cass index --full
- # Incremental update (since last scan)
- cass index
- # Watch mode: auto-reindex on file changes
- cass index --watch
- # Force rebuild even if schema unchanged
- cass index --full --force-rebuild
- # Safe retries with idempotency key (24h TTL)
- cass index --full --idempotency-key "build-$(date +%Y%m%d)"
- # JSON output with stats
- cass index --full --json
- ```
- ### Search
- ```bash
- # Basic search (JSON output required for agents!)
- cass search "query" --robot
- # With filters
- cass search "error" --robot --agent claude --days 7
- cass search "bug" --robot --workspace /path/to/project
- cass search "panic" --robot --today
- # Time filters
- cass search "auth" --robot --since 2024-01-01 --until 2024-01-31
- cass search "test" --robot --yesterday
- cass search "fix" --robot --week
- # Wildcards
- cass search "auth*" --robot # prefix: authentication, authorize
- cass search "*tion" --robot # suffix: authentication, exception
- cass search "*config*" --robot # substring: misconfigured
- # Token budget management (critical for LLMs!)
- cass search "error" --robot --fields minimal # path, line, agent only
- cass search "error" --robot --fields summary # adds title, score
- cass search "error" --robot --max-content-length 500 # truncate fields
- cass search "error" --robot --max-tokens 2000 # soft budget (~4 chars/token)
- cass search "error" --robot --limit 5 # cap results
- # Pagination (cursor-based)
- cass search "TODO" --robot --robot-meta --limit 20
- # Use _meta.next_cursor from response:
- cass search "TODO" --robot --robot-meta --limit 20 --cursor "eyJ..."
- # Match highlighting
- cass search "authentication error" --robot --highlight
- # Query analysis/debugging
- cass search "auth*" --robot --explain # parsed query, cost estimates
- cass search "auth error" --robot --dry-run # validate without executing
- # Aggregations (server-side counts)
- cass search "error" --robot --aggregate agent,workspace,date
- # Request correlation
- cass search "bug" --robot --request-id "req-12345"
- # Source filtering (for multi-machine setups)
- cass search "auth" --robot --source laptop
- cass search "error" --robot --source remote
- # Traceability (for debugging agent pipelines)
- cass search "error" --robot --trace-file /tmp/cass-trace.json
- ```
- ### Session Analysis
- ```bash
- # Export conversation to markdown/HTML/JSON
- cass export /path/to/session.jsonl --format markdown -o conversation.md
- cass export /path/to/session.jsonl --format html -o conversation.html
- cass export /path/to/session.jsonl --format json --include-tools
- # Expand context around a line (from search result)
- cass expand /path/to/session.jsonl -n 42 -C 5 --json
- # Shows 5 messages before and after line 42
- # View source at line
- cass view /path/to/session.jsonl -n 42 --json
- # Activity timeline
- cass timeline --today --json --group-by hour
- cass timeline --days 7 --json --agent claude
- cass timeline --since 7d --json
- # Find related sessions for a file
- cass context /path/to/source.ts --json
- ```
- ### Status & Diagnostics
- ```bash
- # Readiness diagnosis, when needed; not a prerequisite for every query
- cass health --json
- # Full status snapshot
- cass status --json
- cass state --json # alias
- # Statistics
- cass stats --json
- cass stats --by-source # for multi-machine
- # Full diagnostics
- cass diag --verbose
- ```
- ---
- ## Aggregation & Analytics
- Aggregate search results server-side to get counts and distributions without transferring full result data:
- Aggregations reduce output volume, not necessarily scan work. They are not the
- first step for a quick history question; use the scoped retrieval recipe above.
- ```bash
- # 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 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 quality (exact, prefix, fuzzy) |
- Top 10 buckets returned per field, with `other_count` for remaining items.
- ---
- ## Remote Sources (Multi-Machine Search)
- Search across sessions from multiple machines via SSH/rsync.
- ### Setup Wizard (Recommended)
- ```bash
- cass sources setup
- ```
- The wizard:
- 1. Discovers SSH hosts from `~/.ssh/config`
- 2. Probes each for agent data and cass installation
- 3. Optionally installs cass on remotes
- 4. Indexes sessions on remotes
- 5. Configures `sources.toml`
- 6. Syncs data locally
- ```bash
- cass sources setup --hosts css,csd,yto # Specific hosts only
- cass sources setup --dry-run # Preview without changes
- cass sources setup --resume # Resume interrupted setup
- ```
- ### Manual Setup
- ```bash
- # Add a remote machine
- cass sources add user@laptop.local --preset macos-defaults
- cass sources add dev@workstation --path ~/.claude/projects --path ~/.codex/sessions
- # List sources
- cass sources list --json
- # Sync sessions
- cass sources sync
- cass sources sync --source laptop --verbose
- # Check connectivity
- cass sources doctor
- cass sources doctor --source laptop --json
- # Path mappings (rewrite remote paths to local)
- cass sources mappings list laptop
- cass sources mappings add laptop --from /home/user/projects --to /Users/me/projects
- cass sources mappings test laptop /home/user/projects/myapp/src/main.rs
- # Remove source
- cass sources remove laptop --purge -y
- ```
- Configuration stored in `~/.config/cass/sources.toml` (Linux) or `~/Library/Application Support/cass/sources.toml` (macOS).
- ---
- ## Robot Mode Deep Dive
- ### Self-Documenting API
- CASS teaches agents how to use itself:
- ```bash
- # Quick capability check
- cass capabilities --json
- # Returns: features, connectors, limits
- # Full API schema
- cass introspect --json
- # Returns: all commands, arguments, response shapes
- # Topic-based docs (LLM-optimized)
- 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
- cass robot-docs guide # quick-start walkthrough
- cass robot-docs contracts # API versioning
- cass robot-docs sources # remote sources guide
- ```
- ### Forgiving Syntax (Agent-Friendly)
- CASS auto-corrects common mistakes:
- | What you type | What CASS understands |
- |---------------|----------------------|
- | `cass serach "error"` | `cass search "error"` (typo corrected) |
- | `cass -robot -limit=5` | `cass --robot --limit=5` (single-dash fixed) |
- | `cass --Robot --LIMIT 5` | `cass --robot --limit 5` (case normalized) |
- | `cass find "auth"` | `cass search "auth"` (alias resolved) |
- | `cass --limt 5` | `cass --limit 5` (Levenshtein <=2) |
- **Command Aliases:**
- - `find`, `query`, `q`, `lookup`, `grep` → `search`
- - `ls`, `list`, `info`, `summary` → `stats`
- - `st`, `state` → `status`
- - `reindex`, `idx`, `rebuild` → `index`
- - `show`, `get`, `read` → `view`
- - `docs`, `help-robot`, `robotdocs` → `robot-docs`
- ### Output Formats
- ```bash
- # Pretty-printed JSON (default)
- cass search "error" --robot
- # Streaming JSONL (header + one hit per line)
- cass search "error" --robot-format jsonl
- # Compact single-line JSON
- cass search "error" --robot-format compact
- # With performance metadata
- cass search "error" --robot --robot-meta
- ```
- **Design principle:** stdout = JSON only; diagnostics go to stderr.
- ### Token Budget Management
- LLMs have context limits. Control output size:
- | Flag | Effect |
- |------|--------|
- | `--fields minimal` | Only `source_path`, `line_number`, `agent` |
- | `--fields summary` | Adds `title`, `score` |
- | `--fields score,title,snippet` | Custom field selection |
- | `--max-content-length 500` | Truncate long fields (UTF-8 safe) |
- | `--max-tokens 2000` | Soft budget (~4 chars/token) |
- | `--limit 5` | Cap number of results |
- Truncated fields include `*_truncated: true` indicator.
- ---
- ## Structured Error Handling
- Errors are JSON with actionable hints:
- ```json
- {
- "error": {
- "code": 3,
- "kind": "index_missing",
- "message": "Search index not found",
- "hint": "Run 'cass index --full' to build the index",
- "retryable": false
- }
- }
- ```
- ### Exit Codes
- | Code | Meaning | Action |
- |------|---------|--------|
- | 0 | Success | Parse stdout |
- | 1 | Health check failed | Inspect the reported condition; no automatic rebuild |
- | 2 | Usage error | Fix syntax (hint provided) |
- | 3 | Index/DB missing | Report missing assets; indexing is a separate mutating task |
- | 4 | Network error | Check connectivity |
- | 5 | Data/maintenance failure | Read error kind; preserve the archive and report the blocker |
- | 6 | Incompatible version | Update cass |
- | 7 | Lock/busy | Retry later |
- | 8 | Partial result | Report incomplete coverage; do not silently retry |
- | 9 | Unknown error | Check `retryable` flag |
- Codes are command-specific: consult `cass robot-docs exit-codes` and the JSON
- error kind. Search budget expiry can return exit 0 with `budget.timed_out=true`;
- session-path output instead uses exit 10 for timeout.
- ---
- ## Search Modes
- Three search modes, selectable with `--mode` flag:
- | Mode | Algorithm | Best For |
- |------|-----------|----------|
- | **lexical** | BM25 full-text | Exact term matching, bounded history recipes |
- | **semantic** | Vector similarity | Conceptual queries, "find similar" |
- | **hybrid** (default) | Reciprocal Rank Fusion | Lexical retrieval with semantic refinement when ready |
- ```bash
- cass search "authentication" --mode lexical --robot
- cass search "how to handle user login" --mode semantic --robot
- cass search "auth error handling" --mode hybrid --robot
- ```
- **Hybrid** combines lexical and semantic using RRF:
- ```
- RRF_score = Σ 1 / (60 + rank_i)
- ```
- ---
- ## Pipeline Mode (Chained Search)
- Chain searches by piping session paths:
- ```bash
- # 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
- ```
- 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
- ---
- ## Query Language
- ### Basic Queries
- | Query | Matches |
- |-------|---------|
- | `error` | Messages containing "error" (case-insensitive) |
- | `python error` | Both "python" AND "error" |
- | `"authentication failed"` | Exact phrase |
- ### Boolean Operators
- | Operator | Example | Meaning |
- |----------|---------|---------|
- | `AND` | `python AND error` | Both terms required (default) |
- | `OR` | `error OR warning` | Either term matches |
- | `NOT` | `error NOT test` | First term, excluding second |
- | `-` | `error -test` | Shorthand for NOT |
- ```bash
- # Complex boolean query
- cass search "authentication AND (error OR failure) NOT test" --robot
- # Exclude test files
- cass search "bug fix -test -spec" --robot
- # Either error type
- cass search "TypeError OR ValueError" --robot
- ```
- ### Wildcard Patterns
- | Pattern | Type | Performance |
- |---------|------|-------------|
- | `auth*` | Prefix | Fast (edge n-grams) |
- | `*tion` | Suffix | Slower (regex) |
- | `*config*` | Substring | Slowest (regex) |
- ### Match Types
- Results include `match_type`:
- | Type | Meaning | Score Boost |
- |------|---------|-------------|
- | `exact` | Verbatim match | Highest |
- | `prefix` | Via prefix expansion | High |
- | `suffix` | Via suffix pattern | Medium |
- | `substring` | Via substring pattern | Lower |
- | `fuzzy` | Auto-fallback (sparse results) | Lowest |
- ### Auto-Fuzzy Fallback
- When exact query returns <3 results, CASS automatically retries with wildcards:
- - `auth` → `*auth*`
- - Results flagged with `wildcard_fallback: true`
- ### Flexible Time Input
- CASS accepts a wide variety of time/date formats:
- | Format | Examples |
- |--------|----------|
- | **Relative** | `-7d`, `-24h`, `-30m`, `-1w` |
- | **Keywords** | `now`, `today`, `yesterday` |
- | **ISO 8601** | `2024-11-25`, `2024-11-25T14:30:00Z` |
- | **US Dates** | `11/25/2024`, `11-25-2024` |
- | **Unix Timestamp** | `1732579200` (seconds or milliseconds) |
- ---
- ## Ranking Modes
- Cycle with `F12` in TUI or use `--ranking` flag:
- | Mode | Formula | Best For |
- |------|---------|----------|
- | **Recent Heavy** | `relevance*0.3 + recency*0.7` | "What was I working on?" |
- | **Balanced** | `relevance*0.5 + recency*0.5` | General search |
- | **Relevance** | `relevance*0.8 + recency*0.2` | "Best explanation of X" |
- | **Match Quality** | Penalizes fuzzy matches | Precise technical searches |
- | **Date Newest** | Pure chronological | Recent activity |
- | **Date Oldest** | Reverse chronological | "When did I first..." |
- ### Score Components
- - **Text Relevance (BM25)**: Term frequency, inverse document frequency, length normalization
- - **Recency**: Exponential decay (today ~1.0, last week ~0.7, last month ~0.3)
- - **Match Exactness**: Exact phrase=1.0, Prefix=0.9, Suffix=0.8, Substring=0.6, Fuzzy=0.4
- ### Blended Scoring Formula
- ```
- Final_Score = BM25_Score × Match_Quality + α × Recency_Factor
- ```
- | Mode | α Value | Effect |
- |------|---------|--------|
- | Recent Heavy | 1.0 | Recency dominates |
- | Balanced | 0.4 | Moderate recency boost |
- | Relevance Heavy | 0.1 | BM25 dominates |
- | Match Quality | 0.0 | Pure text matching |
- ---
- ## Supported Agents (23 Connectors)
- | Agent | Location | Format |
- |-------|----------|--------|
- | **Claude Code** | `~/.claude/projects` | JSONL |
- | **Codex** | `~/.codex/sessions` | JSONL (Rollout) |
- | **Gemini CLI** | `~/.gemini/tmp` | JSON |
- | **Cline** | VS Code global storage | Task directories |
- | **OpenCode** | `.opencode` directories | SQLite |
- | **Amp** | `~/.local/share/amp` + VS Code | Mixed |
- | **Cursor** | `~/Library/Application Support/Cursor` | SQLite (state.vscdb) |
- | **ChatGPT** | `~/Library/Application Support/com.openai.chat` | JSON (v1 unencrypted) |
- | **Aider** | `~/.aider.chat.history.md` + per-project | Markdown |
- | **Pi-Agent** | `~/.pi/agent/sessions` | JSONL with thinking |
- | **Factory (Droid)** | `~/.factory/sessions` | JSONL by workspace |
- | **GitHub Copilot Chat** | VS Code global storage | JSON / SQLite |
- | **GitHub Copilot CLI** | `~/.copilot/session-state` | JSONL |
- | **OpenClaw** | `~/.openclaw` | JSONL |
- | **ClawdBot** | `~/.clawdbot` | JSONL |
- | **Vibe** | `~/.vibe/logs/session` | JSONL |
- | **Crush** | `~/.crush/crush.db` | SQLite |
- | **Hermes** | `~/.hermes` | JSONL |
- | **Kimi Code** | `~/.kimi/sessions` | JSONL |
- | **Qwen Code** | `~/.qwen/tmp` | JSON / JSONL |
- | **OpenHands** | `~/.openhands/conversations` | JSON event stream |
- | **Antigravity** | `~/.gemini/antigravity-cli` | JSONL / SQLite |
- | **Grok Build** | `$GROK_HOME/sessions` (default `~/.grok/sessions`) | ACP updates JSONL |
- **Note:** ChatGPT v2/v3 are AES-256-GCM encrypted (keychain access required). Legacy v1 unencrypted conversations are indexed automatically.
- ---
- ## TUI Features (for Humans)
- Launch with `cass` (no flags):
- ### Keyboard Shortcuts
- **Navigation:**
- - `Up/Down`: Move selection
- - `Left/Right`: Switch panes
- - `Tab/Shift+Tab`: Cycle focus
- - `Enter`: Open in `$EDITOR`
- - `Space`: Full-screen detail view
- - `Home/End`: Jump to first/last result
- - `PageUp/PageDown`: Scroll by page
- **Filtering:**
- - `F3`: Agent filter
- - `F4`: Workspace filter
- - `F5/F6`: Time filters (from/to)
- - `Shift+F3`: Scope to current result's agent
- - `Shift+F4`: Clear workspace filter
- - `Shift+F5`: Cycle presets (24h/7d/30d/all)
- - `Ctrl+Del`: Clear all filters
- **Modes:**
- - `F2`: Toggle theme (6 presets)
- - `F7`: Context window size (S/M/L/XL)
- - `F9`: Match mode (prefix/standard)
- - `F12`: Ranking mode
- - `Ctrl+B`: Toggle border style
- **Selection & Actions:**
- - `m`: Toggle selection
- - `Ctrl+A`: Select all
- - `A`: Bulk actions menu
- - `Ctrl+Enter`: Add to queue
- - `Ctrl+O`: Open all queued
- - `y`: Copy path/content
- - `Ctrl+Y`: Copy all selected
- - `/`: Find in detail pane
- - `n/N`: Next/prev match
- **Views & Palette:**
- - `Ctrl+P`: Command palette
- - `1-9`: Load saved view
- - `Shift+1-9`: Save view to slot
- **Source Filtering (multi-machine):**
- - `F11`: Cycle source filter (all/local/remote)
- - `Shift+F11`: Source selection menu
- **Global:**
- - `Ctrl+C`: Quit
- - `F1` or `?`: Toggle help
- - `Ctrl+Shift+R`: Force re-index
- - `Ctrl+Shift+Del`: Reset all TUI state
- ### Detail Pane Tabs
- | Tab | Content | Switch With |
- |-----|---------|-------------|
- | **Messages** | Full conversation with markdown | `[` / `]` |
- | **Snippets** | Keyword-extracted summaries | `[` / `]` |
- | **Raw** | Unformatted JSON/text | `[` / `]` |
- ### Context Window Sizing
- | Size | Characters | Use Case |
- |------|------------|----------|
- | **Small** | ~200 | Quick scanning |
- | **Medium** | ~400 | Default balanced view |
- | **Large** | ~800 | Longer passages |
- | **XLarge** | ~1600 | Full context, code review |
- **Peek Mode** (`Ctrl+Space`): Temporarily expand to XL without changing default.
- ---
- ## Theme Presets
- Cycle through 6 built-in themes with `F2`:
- | Theme | Description | Best For |
- |-------|-------------|----------|
- | **Dark** | Tokyo Night-inspired deep blues | Low-light environments |
- | **Light** | High-contrast light background | Bright environments |
- | **Catppuccin** | Warm pastels, reduced eye strain | All-day coding |
- | **Dracula** | Purple-accented dark theme | Popular developer theme |
- | **Nord** | Arctic-inspired cool tones | Calm, focused work |
- | **High Contrast** | Maximum readability | Accessibility needs |
- All themes validated against WCAG contrast requirements (4.5:1 minimum for text).
- ### Role-Aware Message Styling
- | Role | Visual Treatment |
- |------|------------------|
- | **User** | Blue-tinted background, bold |
- | **Assistant** | Green-tinted background |
- | **System** | Gray/muted background |
- | **Tool** | Orange-tinted background |
- ---
- ## Saved Views
- Save filter configurations to 9 slots for instant recall.
- **What Gets Saved:**
- - Active filters (agent, workspace, time range)
- - Current ranking mode
- - The search query
- **Keyboard:**
- - `Shift+1` through `Shift+9`: Save current view
- - `1` through `9`: Load view from slot
- **Via Command Palette:** `Ctrl+P` → "Save/Load view"
- Views persist in `tui_state.json` across sessions.
- ---
- ## Density Modes
- Control lines per search result. Cycle with `Shift+D`:
- | Mode | Lines | Best For |
- |------|-------|----------|
- | **Compact** | 3 | Maximum results visible |
- | **Cozy** | 5 | Balanced view (default) |
- | **Spacious** | 8 | Detailed preview |
- ---
- ## Bookmark System
- Save important results with notes and tags:
- In TUI: Press `b` to bookmark, add notes and tags.
- **Bookmark Structure:**
- - `title`: Short description
- - `source_path`, `line_number`, `agent`, `workspace`
- - `note`: Your annotations
- - `tags`: Comma-separated labels
- - `snippet`: Extracted content
- Storage: `~/.local/share/coding-agent-search/bookmarks.db` (SQLite)
- ---
- ## Optional Semantic Search
- Local-only semantic search using MiniLM (no cloud):
- **Required files** (place in data directory):
- - `model.onnx`
- - `tokenizer.json`
- - `config.json`
- - `special_tokens_map.json`
- - `tokenizer_config.json`
- Vector index stored as `vector_index/index-minilm-384.cvvi`.
- CASS does NOT auto-download models; you must manually install them.
- **Hash Embedder Fallback:** When MiniLM not installed, CASS uses a hash-based embedder for approximate semantic similarity.
- ---
- ## Watch Mode
- Real-time index updates:
- ```bash
- cass index --watch
- ```
- - **Debounce:** 2 seconds (wait for burst to settle)
- - **Max wait:** 5 seconds (force flush during continuous activity)
- - **Incremental:** Only re-scans modified files
- TUI automatically starts watch mode in background.
- ---
- ## Deduplication Strategy
- CASS uses multi-layer deduplication:
- 1. **Message Hash**: SHA-256 of `(role + content + timestamp)` - identical messages stored once
- 2. **Conversation Fingerprint**: Hash of first N message hashes - detects duplicate files
- 3. **Search-Time Dedup**: Results deduplicated by content similarity
- **Noise Filtering:**
- - Empty messages and pure whitespace
- - System prompts (unless searching for them)
- - Repeated tool acknowledgments
- ---
- ## Performance Characteristics
- Latency and memory depend on archive size, index readiness, model state, and
- whether the process is cold. Historical small-corpus timings are not deadlines
- for a large archive. Measure the complete command, bound each retrieval attempt,
- and distinguish successful results from timeout or maintenance refusal.
- ---
- ## Response Shapes
- **Search Response:**
- ```json
- {
- "query": "error",
- "limit": 10,
- "count": 5,
- "total_matches": 42,
- "hits": [
- {
- "source_path": "/path/to/session.jsonl",
- "line_number": 123,
- "agent": "claude_code",
- "workspace": "/projects/myapp",
- "title": "Authentication debugging",
- "snippet": "The error occurs when...",
- "score": 0.85,
- "match_type": "exact",
- "created_at": "2024-01-15T10:30:00Z"
- }
- ],
- "_meta": {
- "elapsed_ms": 12,
- "cache_hit": true,
- "wildcard_fallback": false,
- "next_cursor": "eyJ...",
- "index_freshness": { "stale": false, "age_seconds": 120 }
- }
- }
- ```
- **Aggregation Response:**
- ```json
- {
- "aggregations": {
- "agent": {
- "buckets": [
- {"key": "claude_code", "count": 120},
- {"key": "codex", "count": 85}
- ],
- "other_count": 15
- }
- }
- }
- ```
- ---
- ## Environment Variables
- | Variable | Purpose |
- |----------|---------|
- | `CASS_DATA_DIR` | Override data directory |
- | `CHATGPT_ENCRYPTION_KEY` | Base64 key for encrypted ChatGPT |
- | `PI_CODING_AGENT_DIR` | Override Pi-Agent sessions path |
- | `CASS_CACHE_SHARD_CAP` | Per-shard cache entries (default 256) |
- | `CASS_CACHE_TOTAL_CAP` | Total cached hits (default 2048) |
- | `CASS_DEBUG_CACHE_METRICS` | Enable cache debug logging |
- | `CODING_AGENT_SEARCH_NO_UPDATE_PROMPT` | Skip update checks |
- ---
- ## Shell Completions
- ```bash
- cass completions bash > ~/.local/share/bash-completion/completions/cass
- cass completions zsh > "${fpath[1]}/_cass"
- cass completions fish > ~/.config/fish/completions/cass.fish
- cass completions powershell >> $PROFILE
- ```
- ---
- ## API Contract & Versioning
- ```bash
- cass api-version --json
- # → { "version": "0.4.0", "contract_version": "1", "breaking_changes": [] }
- cass introspect --json
- # → Full schema: all commands, arguments, response types
- ```
- **Guaranteed Stable:**
- - Exit codes and their meanings
- - JSON response structure for `--robot` output
- - Flag names and behaviors
- - `_meta` block format
- ---
- ## Integration with CASS Memory (cm)
- CASS provides **episodic memory** (raw sessions). CM extracts **procedural memory** (rules and playbooks):
- ```bash
- # 1. CASS indexes raw sessions
- cass index --full
- # 2. Search for relevant past experience
- cass search "authentication timeout" --robot --limit 10
- # 3. CM reflects on sessions to extract rules
- cm reflect
- ```
- ---
- ## Troubleshooting
- | Issue | Solution |
- |-------|----------|
- | "missing index" / `maintenance-required` | Report the blocker; separate retrieval from authorized indexing/repair |
- | Stale warning | Report the age/coverage; decide separately whether to refresh |
- | Empty results | Check `budget.timed_out`; then reconsider query scope if the attempt completed |
- | JSON parsing errors | Use `--robot-format compact` |
- | Watch not triggering | Check `watch_state.json`, verify file event support |
- | Reset TUI state | `cass tui --reset-state` or `Ctrl+Shift+Del` |
- ---
- ## Installation
- ```bash
- # One-liner install
- curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/coding_agent_session_search/main/install.sh \
- | bash -s -- --easy-mode --verify
- # Windows
- irm https://raw.githubusercontent.com/Dicklesworthstone/coding_agent_session_search/main/install.ps1 | iex
- ```
- ---
- ## Integration with Flywheel
- | Tool | Integration |
- |------|-------------|
- | **CM** | CASS provides episodic memory, CM extracts procedural memory |
- | **NTM** | Robot mode flags for searching past sessions |
- | **Agent Mail** | Search threads across agent history |
- | **BV** | Cross-reference beads with past solutions |
README.md · README · 3,308 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # 🔎 coding-agent-search (cass)
- <div align="center">
- <img src="docs/assets/images/cass_illustration.webp" alt="coding-agent-search (cass) illustration">
- </div>
- 
- 
- 
- 
- **Unified, high-performance TUI to index and search your local coding agent history.**
- Aggregates sessions from Codex, Claude Code, Gemini CLI, Cline, OpenCode, Amp, Cursor, ChatGPT, Aider, Pi-Agent, Pi Durable, Prime Agent, Oh My Pi, GitHub Copilot Chat, Copilot CLI, OpenClaw, Clawdbot, Vibe, Crush, Goose, Hermes, Kimi Code, Muse Code, Qwen Code, Factory (Droid), Antigravity, OpenHands, Grok Build, Grok Bot, Codebuff/Freebuff, Devin CLI, Shelley, Kiro CLI, and Continue into a single, searchable timeline.
- <div align="center">
- ```bash
- curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/coding_agent_session_search/main/install.sh?$(date +%s)" \
- | bash -s -- --easy-mode --verify
- ```
- ```powershell
- # Windows (PowerShell)
- & ([scriptblock]::Create((irm "https://raw.githubusercontent.com/Dicklesworthstone/coding_agent_session_search/main/install.ps1"))) -EasyMode -Verify
- ```
- Installs the latest release by default. Pass `--version <tag>` / `-Version <tag>` to pin a specific version.
- **Or via package managers:**
- ```bash
- # Homebrew (Apple Silicon macOS + Linux)
- brew install dicklesworthstone/tap/cass
- # Windows (Scoop)
- scoop bucket add dicklesworthstone https://github.com/Dicklesworthstone/scoop-bucket
- scoop install dicklesworthstone/cass
- ```
- The Homebrew tap installs prebuilt release tarballs (not bottles) for Linux and Apple Silicon macOS. On Intel macOS, use the install script with `--from-source`.
- </div>
- ---
- ## 🤖 Agent Quickstart (Robot Mode)
- ⚠️ **Never run bare `cass` in an agent context** — it launches the interactive TUI. Always use `--robot` or `--json`.
- ```bash
- # 1) Check the installed interface once per version (recipe verified on 0.10.0).
- cass --version
- cass search --help
- # Verify a newly installed executable without opening the configured archive.
- cass selftest --json
- # `health --binary-only` still reports (and therefore probes) archive readiness.
- # 2) For a quick history question, start with scoped read-only lexical retrieval.
- # Hybrid remains the product default; lexical is explicit for this workflow.
- cass search "performance regression" --workspace /path/to/project --days 7 \
- --mode lexical --no-maintenance --robot --robot-meta --fields minimal \
- --limit 5 --max-tokens 2000 --timeout 2000
- # 3) Find the current or recent session for this workspace
- cass sessions --current --json
- cass sessions --workspace "$(pwd)" --json --limit 5
- # 4) View + expand a hit (use source_path/line_number from search output)
- cass view /path/to/session.jsonl -n 42 -C 3 --json --timeout 2000
- # 5) Discover the full machine API
- cass capabilities --json
- cass robot-docs guide
- cass robot-docs schemas
- # 6) Exclude a noisy agent harness from future indexing
- cass sources agents list --json
- cass sources agents exclude openclaw
- cass sources agents include openclaw
- ```
- The retrieval flags above are available in 0.8.0 and later. On older builds, check help;
- if `--no-maintenance` is absent, report the mismatch instead of dropping the
- read-only constraint. `--timeout` is in milliseconds, while `--max-tokens` limits
- approximate output size. Also set a caller-side deadline (for example, GNU
- `timeout 10s`); an externally interrupted command may leave incomplete JSON.
- Inspect `budget.timed_out` even after exit 0: timed-out empty hits are not proof
- that no history exists. A `maintenance-required` response ends the retrieval
- attempt; indexing or repair is a separate mutating task. Use triage/health/status
- for readiness diagnosis, not as repeated prerequisites to a short summary.
- Broaden scope deliberately, expand useful hits, and preserve source/line citations.
- `view -C` bounds context lines, not bytes; check excerpt size before including
- a long JSONL record in an agent prompt.
- **Output conventions**
- - stdout = data only
- - stderr = diagnostics
- - exit 0 = success
- **Search asset contract**
- - SQLite is the source of truth for indexed conversations and messages. All derived assets (lexical index, semantic vectors, analytics rollups, retention backups) can be rebuilt from SQLite; no derived asset is authoritative.
- - Lexical search is the required fast path. Missing, stale, or incompatible lexical assets are treated as derived-state problems that cass should rebuild from SQLite instead of asking operators to perform routine manual repair.
- - Hybrid is the default search intent. Robot metadata (`--robot --robot-meta`) reports the requested mode, realized mode, semantic refinement status, and any lexical fallback reason when semantic assets are not ready.
- - Semantic assets are opportunistic background enrichment. Lexical-only results are expected during first indexing, semantic catch-up, disabled semantic policy, or unavailable local model/vector files.
- - Semantic model acquisition is **opt-in**: `cass models install` downloads the default `all-minilm-l6-v2` (alias `minilm`, ~90 MB) only on explicit request; `--model multilingual-minilm` selects the larger multilingual MiniLM L12 model (~480 MB) for CJK/mixed-language archives. Cass never auto-downloads or auto-selects the multilingual space. Air-gapped installs use `--from-file <dir>`. While the selected model is absent, hybrid search uses lexical-only and reports `fallback_mode="lexical"` in health/status.
- - `cass triage --json` combines readiness, `next_command`, `recommended_commands[]`, docs/schema pointers, starter workflows, and accepted recoveries for diagnosis. Review recommended mutations before executing them. `cass health --json` and `cass status --json` remain the narrower truth surfaces for readiness, active rebuilds, and recovery.
- **Lexical publish durability (atomic-swap)**
- - Every lexical publish is an atomic renameat2(RENAME_EXCHANGE) on Linux, or a parked-rename + restore-on-failure dance elsewhere. Readers never see a half-torn index — they see either the old or the new generation, never a mix. See `src/indexer/mod.rs::publish_staged_lexical_index`.
- - The prior-live generation is retained under `<data_dir>/index/.lexical-publish-backups/<dated>/` for a bounded retention window. Default cap is `1` (keep just the most-recent prior generation for one-step rollback); override via the `CASS_LEXICAL_PUBLISH_BACKUP_RETENTION` env var (`0` disables retention entirely, higher N keeps deeper history). Pruning runs after every successful publish and emits structured `tracing::info!` events with `freed_bytes` + `retention_limit` for observability.
- - Crash recovery is automatic: a crash between the atomic swap and the retain-rename is handled by `recover_or_finalize_interrupted_lexical_publish_backup` at the start of the next lexical publish or rebuild (not at process startup), which moves any orphaned canonical sidecar (`.<name>.publish-in-progress.bak`) into `.lexical-publish-backups/` before the next publish lands.
- **Quarantine, GC, and the doctor/diag surface**
- - Corrupt or failed-validation assets are quarantined rather than auto-deleted. `cass diag --json --quarantine` enumerates every quarantined derived artifact (failed seed bundles, retained publish backups, quarantined lexical generations; conversations excluded at ingest are listed by `cass quarantine list --json`) with `size_bytes`, `age_seconds`, `safe_to_gc`, and a human-readable `gc_reason`. The `safe_to_gc` flag is **advisory** — it reflects retention policy + cleanup dry-run eligibility and is not wired to any automatic deletion path.
- - `cass doctor --json` surfaces the same quarantine summary plus `checks[]` status for every diagnostic the tool runs. Without `--fix`, doctor is read-only (`auto_fix_applied=false`, `auto_fix_actions=[]`, `issues_fixed=0`); with `--fix` it applies only the repairs whose dry-run plans are proven safe (currently: Track A analytics rebuild, Track B rollup rebuild via `rebuild_token_daily_stats` when the `token_usage` ledger is intact).
- - Lexical generation cleanup uses a dispositions + inspection-required-first policy. Operators running `cass doctor --fix` never have a generation reclaimed silently — every quarantine stays on disk until an explicit derived-asset rebuild (`cass models backfill` or an index refresh recommended by `cass health --json`) supersedes it.
- - A derived (SQLite fallback) FTS repair that fails **identically on 5 consecutive `cass index` runs** escalates from a warning to a non-zero exit ([#434](https://github.com/Dicklesworthstone/coding_agent_session_search/issues/434)): the counter persists in `<data_dir>/index/.fts-repair-failure-streak.json`, watch daemons log the escalation instead of exiting, and any run whose repair succeeds — or fails differently — resets it. Canonical rows and the Tantivy index are unaffected; run `cass doctor --rebuild-canonical-fts --yes --json` for the explicit repair.
- **Schema stability guarantees**
- - JSON contract surfaces are pinned by golden-file regression tests under `tests/golden/robot/`: `capabilities`, `selftest`, `health`, `status`, `diag`, `models status`/`verify`/`check-update`, `introspect`, `doctor`, `api-version`, `stats`, `search`, `export-html`, `onboarding`, the `quarantine` and `dedup` commands and `analytics incidents`, plus `sessions` and `pack` on their missing-database and error paths only. `swarm status` scenarios are pinned under `tests/golden/swarm_status/`. `triage`, `swarm work-packet` and `swarm lint` have no golden files; their shape is covered only by assertion tests. A change to any field name, type, or nullability fails the golden test suite and requires a deliberate regeneration pass (`UPDATE_GOLDENS=1 rch exec -- env CARGO_TARGET_DIR=/data/tmp/cass-golden-target cargo test --test golden_robot_json --test golden_robot_docs`).
- - `cass introspect --json`'s `response_schemas` block enumerates every schema in a stable alphabetical order (`BTreeMap`-backed — see bead coding_agent_session_search-8sl73).
- - Error envelopes (`{error: {code, kind, message, hint, retryable}}`) have a fixed shape. `kind` values are kebab-case; branch on `err.kind`, not on the numeric code, for codes ≥ 10 (see the Error Handling section below).
- ## 📬 Agent Mail Fallback (When MCP Tools Are Not Exposed)
- If your runtime does not expose built-in `mcp-agent-mail` tools (for example, `list_mcp_resources` is empty), you can still coordinate via direct MCP HTTP calls.
- ### 1) Start the local Agent Mail server
- ```bash
- ~/.local/pipx/venvs/mcp-agent-mail/bin/python -m mcp_agent_mail.cli serve-http --host 127.0.0.1 --port 8765
- ```
- ### 2) Use the Streamable HTTP MCP endpoint (`/mcp`)
- ```bash
- curl -sS -X POST http://127.0.0.1:8765/mcp \
- -H 'Content-Type: application/json' \
- -d '{"jsonrpc":"2.0","id":"health","method":"tools/call","params":{"name":"health_check","arguments":{}}}'
- ```
- ### 3) Minimal coordination flow (project -> agent -> message -> inbox -> ack)
- ```bash
- # Ensure project
- curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
- '{"jsonrpc":"2.0","id":"ensure","method":"tools/call","params":{"name":"ensure_project","arguments":{"human_key":"/data/projects/coding_agent_session_search"}}}'
- # Register agent
- curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
- '{"jsonrpc":"2.0","id":"register","method":"tools/call","params":{"name":"register_agent","arguments":{"project_key":"/data/projects/coding_agent_session_search","program":"codex","model":"gpt-5","name":"YourAgentName"}}}'
- # Send message
- curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
- '{"jsonrpc":"2.0","id":"send","method":"tools/call","params":{"name":"send_message","arguments":{"project_key":"/data/projects/coding_agent_session_search","sender_name":"YourAgentName","to":["PeerAgent"],"subject":"[coord] hello","thread_id":"coord-2026-02-13","ack_required":true,"body_md":"Online and starting work."}}}'
- # Fetch inbox
- curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
- '{"jsonrpc":"2.0","id":"inbox","method":"tools/call","params":{"name":"fetch_inbox","arguments":{"project_key":"/data/projects/coding_agent_session_search","agent_name":"YourAgentName","limit":50,"include_bodies":true}}}'
- # Acknowledge message id 42
- curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
- '{"jsonrpc":"2.0","id":"ack","method":"tools/call","params":{"name":"call_extended_tool","arguments":{"tool_name":"acknowledge_message","arguments":{"project_key":"/data/projects/coding_agent_session_search","agent_name":"YourAgentName","message_id":42}}}}'
- ```
- ### Important caveat
- `mcp_agent_mail` defaults to `sqlite+aiosqlite:///./storage.sqlite3`. That means the server working directory determines which mailbox database you are using. To avoid "project not found" confusion, start the server from the same directory your team expects for mailbox state.
- ## 📸 Screenshots
- <div align="center">
- ### Search Results Across All Your Agents
- *Three-pane layout with semantic styling: filter bar with pills, results list with color-coded agents and score tiers, and syntax-highlighted detail preview with tab navigation*
- <img src="docs/assets/screenshots/screenshot_01.webp" alt="Main TUI showing search results across multiple coding agents" width="800">
- ---
- ### Rich Conversation Detail View
- *Full conversation rendering with markdown formatting, code blocks, headers, and structured content*
- <img src="docs/assets/screenshots/screenshot_02.webp" alt="Detail view showing formatted conversation content" width="800">
- ---
- ### Quick Start & Keyboard Reference
- *Built-in help screen (press `F1` or `?`) with all shortcuts, filters, modes, and navigation tips*
- <img src="docs/assets/screenshots/screenshot_03.webp" alt="Help screen showing keyboard shortcuts and features" width="500">
- </div>
- ---
- ## 💡 Why This Exists
- ### The Problem
- AI coding agents are transforming how we write software. Claude Code, Codex, Cursor, Copilot, Aider, Pi-Agent; each creates a trail of conversations, debugging sessions, and problem-solving attempts. But this wealth of knowledge is **scattered and unsearchable**:
- - **Fragmented storage**: Each agent stores data differently—JSONL files, SQLite databases, markdown logs, proprietary JSON formats
- - **No cross-agent visibility**: Solutions discovered in Cursor are invisible when you're using Claude Code
- - **Lost context**: That brilliant debugging session from two weeks ago? Good luck finding it by scrolling through files
- - **No semantic search by default**: File-based grep doesn't understand natural language queries; cass can add optional local ML search when model files are installed
- ### The Solution
- `cass` treats your coding agent history as a **unified knowledge base**. It:
- 1. **Normalizes** disparate formats into a common schema
- 2. **Indexes** everything with a purpose-built full-text search engine
- 3. **Surfaces** relevant past conversations in milliseconds
- 4. **Respects** your privacy—everything stays local, nothing phones home
- ### Who Benefits
- - **Individual developers**: Find that solution you know you've seen before
- - **Teams**: Share institutional knowledge across different tool preferences
- - **AI agents themselves**: Let your current agent learn from all your past agents (via robot mode)
- - **Power users**: Build workflows that leverage your complete coding history
- ---
- ## ✨ Key Features
- ### ⚡ Instant Search (Sub-60ms Latency)
- - **"Search-as-you-type"**: Results update instantly with every keystroke.
- - **Edge N-Gram Indexing**: We frontload the work by pre-computing prefix matches (e.g., "cal" -> "calculate") during indexing: 2–20 character prefixes of every word in titles and in the first 4 KiB of each message, trading disk space for fast lookup at query time.
- - **Smart Tokenization**: Handles `snake_case` ("my_var" matches "my" and "var"), hyphenated terms, and code symbols (`c++`, `foo.bar`) correctly.
- - **Zero-Stall Updates**: The background indexer commits changes atomically; `reader.reload()` ensures new messages appear in the search bar immediately without restarting.
- - **One-shot CLI overhead**: the sub-60ms figure is the engine query. A one-shot `cass search --robot` currently spends roughly a second in archive open and integrity preflight on a ~10 GB archive; `--robot-meta` reports that separately as `_meta.timing.other_ms`, while `search_ms` stays in the tens of milliseconds.
- ### 🧠 Optional Semantic Search (Local by Default)
- - **Local inference**: Uses frankensearch's pure-Rust native MiniLM implementation with local safetensors weights. Once MiniLM is installed, no network traffic is required to answer queries.
- - **Warm-daemon reuse**: Semantic and hybrid CLI searches automatically use an
- already-running local embedding daemon (including a socket selected with
- `CASS_DAEMON_SOCKET`) and only initialize the installed in-process model if
- daemon inference fails. Pass `--daemon` to permit auto-spawning a missing
- daemon in human-mode searches (robot/JSON searches never spawn one, even
- with `--daemon`, because their bounded budget cannot wait for a daemon to
- start; start `cass daemon` yourself first; `_meta.effective.daemon` shows
- the request and what applied), or `--no-daemon` to force
- direct inference. `--fast-only` stays in
- the deterministic hash-vector space. Each data directory gets a distinct
- default socket and owner-private pinned key; fresh handshake, health,
- embedding, batch, and rerank challenges authenticate the exact response and
- immutable Frankensearch embedding identity before any daemon output is used.
- `--two-tier` progressive refinement (fast results refined in place by the
- quality tier) is experimental and currently inactive: the one-shot CLI
- collapses it to a single-tier quality search and the TUI's progressive lanes
- are disabled at HEAD, so hybrid search today is lexical plus one MiniLM
- refinement pass when the model is installed.
- - **Opt-in acquisition**: `cass models install` downloads `all-minilm-l6-v2` from Hugging Face on explicit request and verifies SHA256 checksums. `cass models install --model multilingual-minilm` explicitly selects `paraphrase-multilingual-MiniLM-L12-v2` for CJK and mixed-language retrieval. Nothing is fetched until an install command runs, and merely installing the multilingual model never changes the active space.
- - **Air-gapped install**: `cass models install --model <minilm|multilingual-minilm> --from-file <dir>` accepts a pre-downloaded model directory so you can bring the assets in yourself.
- - **Switching spaces**: both models output 384 values, but their identities and vectors are incompatible. Set `CASS_SEMANTIC_EMBEDDER=multilingual-minilm`, then run `cass models backfill --tier quality --embedder multilingual-minilm`; cass keeps lexical fail-open active until the complete new generation is atomically published.
- - **Required files** (all must be present after install; `cass models verify --model <minilm|multilingual-minilm>` checks the selected model):
- - `model.safetensors`
- - `tokenizer.json`
- - `config.json`
- - `special_tokens_map.json`
- - `tokenizer_config.json`
- - **Vector index**: Stored as `vector_index/index-<embedder>.fsvi` in the data directory.
- - **Lexical fail-open**: While the model is absent, `cass` returns lexical-only results and reports `fallback_mode="lexical"` in health/status; search never blocks on semantic assets.
- #### Opt-In External Embeddings
- An OpenAI-compatible embedding service can own inference, including any GPU it supports. Select `external` explicitly and set `CASS_EXTERNAL_EMBEDDINGS=1` to consent to sending selected archive text during backfill and query text during semantic search. Configuring a URL alone sends nothing. Local models and hash embeddings keep their existing behavior.
- Configure the endpoint's actual model name, output dimension and a stable model revision before backfilling. This example assumes a loopback service producing 384-dimensional vectors:
- ```bash
- export CASS_EXTERNAL_EMBEDDINGS=1
- export CASS_EXTERNAL_EMBEDDING_URL='http://127.0.0.1:8000/v1/embeddings'
- export CASS_EXTERNAL_EMBEDDING_MODEL='your-model-name'
- export CASS_EXTERNAL_EMBEDDING_DIMENSION=384
- export CASS_EXTERNAL_EMBEDDING_REVISION='model-revision-1'
- # Set CASS_EXTERNAL_EMBEDDING_API_KEY separately if the service requires it.
- cass models backfill --tier quality --embedder external --data-dir /path/to/cass-data --json
- CASS_SEMANTIC_EMBEDDER=external cass search 'your query' --mode semantic --data-dir /path/to/cass-data --json
- ```
- Use HTTPS for a non-loopback endpoint. Redirects and URLs containing credentials, a query or a fragment are refused. Responses must name the configured model and supply finite, unit-normalized vectors of the declared dimension. Fixed public probes check dimensions, normalization and repeatability before archive/query text is sent. Endpoint, model, dimension and revision identify a separate vector space; changing them requires its own completed backfill, while credential rotation preserves the space. Provider errors retain durable backfill checkpoints. A blocking request remains bounded by `CASS_EXTERNAL_EMBEDDING_TIMEOUT_MS` when cancellation occurs.
- The persistent service also accepts `--semantic-embedder external` with `--data-dir` and `--db`; it uses the same consent and publication admission. `cass capabilities --json` and `cass robot-docs env` list every provider setting and default without printing configured values or contacting the endpoint. External protocol tests use a synthetic loopback service; they establish neither GPU performance nor a provider's retrieval quality.
- #### Explicit Hash Vector Tier
- The deterministic hash embedder is available only when explicitly selected, such as with `--fast-only`, `--embedder hash`, or `CASS_SEMANTIC_EMBEDDER=hash`. It is a separate lexical-feature vector space, not a silent substitute for missing MiniLM vectors:
- | Feature | ML Model (MiniLM) | Hash Embedder (FNV-1a) |
- |---------|-------------------|------------------------|
- | **Meaning Understanding** | ✅ "car" ≈ "automobile" | ❌ Exact tokens only |
- | **Initialization Time** | ~500ms (model loading) | <1ms (instant) |
- | **Network Dependency** | None (after install) | None |
- | **Disk Footprint** | ~90MB model files | 0 bytes |
- | **Deterministic** | ✅ Same input = same output | ✅ Same input = same output |
- **Algorithm**:
- 1. **Tokenize**: Lowercase, split on non-alphanumeric, filter tokens <2 characters
- 2. **Hash**: Apply FNV-1a to each token
- 3. **Project**: Use hash to determine dimension index and sign (+1 or -1) in a 384-dimensional vector
- 4. **Normalize**: L2 normalize to unit length for cosine similarity
- **When to Use**:
- - Quick setup without downloading model files
- - Environments where ML inference overhead is unwanted
- - Fast-tier testing or an explicitly chosen degraded mode
- **Override**: Set `CASS_SEMANTIC_EMBEDDER=hash` to force hash mode even when ML model is available.
- #### FSVI Vector Index Format
- `cass` uses the **frankensearch FSVI** vector index format (`.fsvi`) for storing semantic embeddings.
- **Features**:
- - **Memory-mappable**: large indexes open without copying into RAM
- - **Quantization**: supports `f32` and `f16` storage for smaller on-disk size
- - **Fast search**: exact brute-force vector search by default; HNSW approximate search runs only when `--approximate` is passed and the HNSW sidecar file exists. In `status --json`, `hnsw_present` and `hnsw_state` (`present_unverified` when a sidecar file exists) report the sidecar; `hnsw_ready` is currently always `false`, because status does not verify native ANN admission
- **Index Location**: `~/.local/share/coding-agent-search/vector_index/index-<embedder>.fsvi`
- #### Search Modes
- `cass` supports three search modes, selectable via `--mode` flag or `Alt+S` in the TUI:
- | Mode | Algorithm | Best For |
- |------|-----------|----------|
- | **Lexical** | BM25 full-text | Exact term matching, code searches |
- | **Semantic** | Vector similarity | Conceptual queries, "find similar" |
- | **Hybrid** (default) | Lexical + single-tier semantic refinement fused with RRF; lexical fail-open | Balanced precision and recall |
- **Lexical Search**: Uses Quill's BM25 implementation with prefix matching. Best when you know the exact terms you're looking for. The lexical index is derived from SQLite; if it is missing, stale, or incompatible, cass reports the state and rebuilds through the normal indexing path from the canonical database.
- **Semantic Search**: Computes vector similarity between query and indexed MiniLM embeddings. Finds conceptually related content even without exact term overlap. Explicit semantic mode requires the MiniLM model and a compatible MiniLM vector index; it never substitutes same-dimensional hash vectors.
- **Hybrid Search**: The default. It combines lexical and semantic results using Reciprocal Rank Fusion (RRF) when semantic assets are ready, and it fails open to lexical when semantic enrichment is still catching up or disabled:
- ```
- RRF_score = Σ 1 / (K + rank_i)
- ```
- Where K=60 (tuning constant) and rank_i is the position in each result list. This balances the precision of lexical search with the recall of semantic search. Semantic refinement is a single pass over the installed MiniLM index; progressive two-tier refinement (`--two-tier`) is experimental and currently inactive.
- ```bash
- # CLI examples
- cass search "authentication" --mode lexical --robot
- cass search "how to handle user login" --mode semantic --robot
- cass search "auth error handling" --mode hybrid --robot
- ```
- ### 🎯 Advanced Search Features
- - **Wildcard Patterns**: Full glob-style pattern support:
- - `foo*` - Prefix match (finds "foobar", "foo123")
- - `*foo` - Suffix match (finds "barfoo", "configfoo")
- - `*foo*` - Substring match (finds "afoob", "configuration")
- - **Auto-Fuzzy Fallback**: On small indexes (up to 10,000 documents by default), an exact search with sparse results is retried with `*term*` wildcards to broaden matches. A visual indicator shows when the fallback is active.
- - **Query History Deduplication**: Recent searches deduplicated to show unique queries; navigate with `Up`/`Down` arrows.
- - **Match Quality Ranking**: New ranking mode (cycle with `F12`) that prioritizes exact matches over wildcard/fuzzy results.
- - **Match Highlighting**: Snippets mark the terms the engine matched with `**bold**`, in human-readable and robot/JSON output alike; `--highlight` also marks the query terms' other occurrences, never marking a term twice.
- ### 🖥️ Rich Terminal UI (TUI)
- Powered by [FrankenTUI (ftui)](https://github.com/Dicklesworthstone/frankentui) — a high-performance Elm-architecture TUI framework with adaptive frame budgets, Bayesian diff selection, and spring-based animations.
- - **Three-Pane Layout**: Filter bar (top), scrollable results (left), and syntax-highlighted details (right).
- - **Multi-Line Result Display**: Each result shows location and up to 3 lines of context; alternating stripes improve scanability.
- - **Live Status**: Footer shows real-time indexing progress—agent discovery count during scanning, then item progress as a progress bar labelled `Indexing 150/2000 (7%)`—plus active filters.
- - **Multi-Open Queue**: Queue multiple results with `Ctrl+Enter`, then open all in your editor with `Ctrl+O`. Confirmation prompt for large batches (≥12 items).
- - **Find-in-Detail**: Press `/` to search within the detail pane; matches highlighted with `n`/`N` navigation.
- - **Mouse Support**: Click to select results, scroll panes, or clear filters.
- - **Theming**: Adaptive Dark/Light modes with role-colored messages (User/Assistant/System). Presets include dark, light, high-contrast, and accessible variants.
- - **Ranking Modes**: Cycle through `recent`/`balanced`/`relevance`/`quality` with `F12`; quality mode penalizes fuzzy matches.
- - **Analytics Dashboard**: 7 views (Dashboard, Explorer, Heatmap, Breakdowns, Tools, Plans, Coverage) with interactive charts, KPI tiles, and drill-down filtering. Open with `Alt+A`; `Esc` returns to search.
- - **Inline Mode**: Run `cass tui --inline` to keep terminal scrollback intact. The UI anchors to a region of the terminal while logs scroll normally. Configure with `--ui-height <rows>` and `--anchor top|bottom`.
- - **Macro Recording**: Capture input sessions with `cass tui --record-macro session.macro` for reproducible bug reports and workflow automation. Events are saved as human-readable JSONL with full timing data.
- - **Asciicast Recording**: Capture reproducible TUI demos and bug repro artifacts with `cass tui --asciicast demo.cast`.
- - Security default: recording captures terminal output only (input keystrokes are not serialized by default).
- ### 📄 HTML Session Export
- Export conversations as styled, portable HTML files with optional encryption:
- - **Mostly Self-Contained**: All layout CSS and the export payload are inlined directly; the file opens without a local web server and references no Tailwind CDN (Tailwind is not used at runtime). Only the Prism.js syntax-highlighting assets are loaded from `cdn.jsdelivr.net`, pinned with SRI hashes.
- - **Progressive Enhancement / Graceful Degradation**: Prism.js resources fall back via `onerror="...no-prism"` — code blocks remain readable offline in plain monospace, and the page layout never depends on a network resource.
- - **Password Protection**: AES-256-GCM encryption with PBKDF2 key derivation (600,000 iterations)—opens directly in any browser
- - **Rich Styling**: Dark/light themes, syntax-highlighted code blocks, collapsible tool calls
- - **Print-Friendly**: Optimized print styles with page breaks and footers
- - **Searchable**: Built-in search functionality within the exported document
- - **Credential redaction**: HTML and generic conversation exports redact recognized credentials by default, including raw source files and archives indexed with redaction disabled. `--include-secrets` explicitly preserves source credentials and marks the output as sensitive. Encryption uses the same sharing policy.
- **TUI Usage**: Press `Ctrl+E` in the detail view to open the export modal, or `Ctrl+Shift+E` to export Markdown immediately with defaults. On the detail pane's Export tab, `e`/`h` open the HTML export modal and `m` runs the Markdown export.
- **CLI Usage**:
- ```bash
- # Basic export
- cass export-html /path/to/session.jsonl
- # With encryption
- printf '%s\n' "secret" | cass export-html /path/to/session.jsonl --encrypt --password-stdin
- # Explicit raw-fidelity export (contains credentials; handle as sensitive)
- cass export-html /path/to/session.jsonl --include-secrets --json
- # Custom output location
- cass export-html session.jsonl --output-dir ~/exports --filename "my-session"
- # Open in browser after export
- cass export-html session.jsonl --open
- # Robot mode (JSON output)
- cass export-html session.jsonl --json
- ```
- ### 🔗 Universal Connectors
- Ingests history from 34 local agent connectors, normalizing them into a unified `Conversation -> Message -> Snippet` model. `cass capabilities --json | jq .connectors` is the canonical machine-readable inventory (kept in lockstep with the runtime registry):
- - **Codex**: `~/.codex/sessions` and `~/.codex/archived_sessions` (Rollout JSONL, plain or zstd-compressed `.jsonl.zst`)
- - **Cline**: VS Code global storage (Task directories)
- - **Gemini CLI**: `~/.gemini/tmp` (Chat JSON)
- - **Claude Code**: `~/.claude/projects` (Session JSONL), plus macOS Desktop metadata sidecars under
- `~/Library/Application Support/Claude/claude-code-sessions` and
- `~/Library/Application Support/Claude/local-agent-mode-sessions`
- - **Clawdbot**: `~/.clawdbot/sessions` (Session JSONL)
- - **Vibe (Mistral)**: `~/.vibe/logs/session/*/messages.jsonl` (Session JSONL)
- - **OpenCode**: `.opencode` directories (SQLite)
- - **Amp**: `~/.local/share/amp` & VS Code storage
- - **Cursor**: `~/Library/Application Support/Cursor/User/` global + workspace storage (SQLite `state.vscdb`)
- - **ChatGPT**: `~/Library/Application Support/com.openai.chat` (v1 unencrypted JSON; v2/v3 encrypted—see Environment)
- - **Aider**: `~/.aider.chat.history.md` and per-project `.aider.chat.history.md` files (Markdown)
- - **Pi-Agent**: `~/.pi/agent/sessions` (Session JSONL with thinking content; `pi_agent_rust` SQLite sessions too)
- - **Pi Durable (`pi_durable`)**: Pi's experimental durable harness (`@earendil-works/pi-durable`). SQLite stores at `<agent dir>/experimental/durable-sessions/<cwd-hash>/<ms>-<uuid>/session.sqlite` (agent dir `PI_CODING_AGENT_DIR` or `~/.pi/agent`); JSONL commit-log stores under explicit roots. Each conversation in a store (lead, forks, task-owned children) is its own conversation. System prompts, task checkpoints and application documents are never indexed, and the stores are not raw-mirrored
- - **Prime Agent (`prime_agent`)**: `~/.prime/agent/sessions/<session-id>.jsonl` (versions 1–3). Indexes the active branch with omission counts for abandoned siblings; preserves thinking, tool results and context summaries. Overrides, in precedence order: `PRIME_AGENT_SESSION_DIR`, legacy `PRIME_AGENT_CODING_AGENT_SESSION_DIR`, then `PRIME_AGENT_CODING_AGENT_DIR` (with `/sessions` appended). Prime retains its own agent identity.
- - **Oh My Pi (`omp`)**: OMP v18's default `~/.omp/agent/sessions`, named profiles under `~/.omp/profiles/<name>/agent/sessions`, XDG stores under `$XDG_DATA_HOME/omp`, and explicit OMP-only archive roots via `CASS_OMP_DATA_ROOT` (pi-family JSONL, including per-session sub-agent transcripts)
- - **GitHub Copilot Chat**: VS Code global storage under `github.copilot-chat` (JSON)
- - **Copilot CLI**: `~/.copilot/session-state`, legacy `~/.copilot/history-session-state`, and `gh copilot` config paths (JSONL/JSON)
- - **OpenClaw**: `~/.openclaw/agents/*/agent/openclaw-agent.sqlite` (native SQLite transcripts) and `~/.openclaw/agents/*/sessions` (legacy JSONL). `OPENCLAW_STATE_DIR` selects a different state directory. Watch mode polls database/WAL/SHM bundles under selected database files, state directories, and remote mirrors, and enrolls native stores created after startup. Discovery checks supported paths and immediate agent directories without walking session logs. Mirrors of `.openclaw` or `.openclaw/agents` support both retained-basename and contents-copy layouts. Native history suppresses a legacy migration copy only within the same physical agent directory, so another mirror's same-named session remains searchable.
- - **Goose**: `~/.local/share/goose/sessions/sessions.db` (SQLite, v1.20+), plus the earlier per-session `*.jsonl` layout under `~/.goose/sessions`
- - **Crush**: `~/.crush/crush.db` and per-project `.crush/crush.db` (SQLite)
- - **Hermes**: `~/.hermes/state.db` and project-local `.hermes/state.db` (SQLite)
- - **Devin CLI**: `~/.local/share/devin/cli/sessions.db` (SQLite; override with `CASS_DEVIN_DATA_ROOT`). Indexes visible local sessions along their active parent chain, preserving tool messages and excluding abandoned branches and inline image payloads. Cloud-only sessions are outside this connector's scope.
- - **Shelley**: reads the local SQLite conversation database directly. Set `CASS_SHELLEY_DB=/absolute/path/to/shelley.db`, or add that file to the `paths` of a `type = "local"` source in `sources.toml`. Any filename is accepted after schema validation. Defaults include `~/.config/shelley/shelley.db` and `shelley.db` in the current directory. Live indexing watches the database and its WAL/SHM sidecars; metadata changes refresh existing sessions. `CASS_SKIP_SUBAGENTS=1` excludes conversations with a Shelley parent ID. The database can also contain credentials and application settings, so raw mirroring and remote database ingestion are disabled; keep the database on its original machine.
- - **Grok Bot**: indexes the desktop application's local rolling chat replica. Set `CASS_GROK_BOT_DATA_ROOT` to its persistence directory. Native message IDs preserve already indexed history as older messages leave the application's window; repeat scans do not duplicate retained messages. CASS reads only chat content. Raw mirroring and automatic fleet copying are disabled because the replica also holds secret and approval fields. This connector is separate from the Grok CLI connector and does not fetch cloud history.
- - **Kimi Code**: `$KIMI_CODE_HOME/sessions/*/*/agents/*/wire.jsonl` (default `~/.kimi-code`; sub-agents index as `<sessionId>:<agentId>`), plus the legacy `~/.kimi/sessions/*/*/wire.jsonl` layout (Session JSONL)
- - **Muse Code**: `~/.local/share/muse/sessions/<YYYY>/<MM>/<DD>/<session-id>/session.jsonl`, including nested `subagent/*/session.jsonl` transcripts (override with `CASS_MUSE_DATA_ROOT`)
- - **Qwen Code**: `~/.qwen/tmp/*/chats/session-*.json` (Chat JSON)
- - **Factory (Droid)**: `~/.factory/sessions` (JSONL files organized by workspace slug)
- - **Antigravity (IDE + agy CLI)**: both stores are probed by default — the IDE's `~/.gemini/antigravity/` and the CLI's `~/.gemini/antigravity-cli/` — each holding `brain/<uuid>/.system_generated/logs/transcript.jsonl` (clean JSONL transcript) with the durable per-conversation `conversations/<uuid>.db` (SQLite) mirrored alongside. IDE conversations are keyed `ide/<uuid>` so the two stores never collide; `CASS_ANTIGRAVITY_DATA_ROOT` replaces both with one explicit base. Resume with `cass resume <transcript> --agent agy` (`agy --conversation <uuid>`).
- - **OpenHands (OpenDevin)**: `~/.openhands/conversations/<id>/` — `base_state.json` metadata plus an `events/event-NNNNN-<uuid>.json` event stream (JSON)
- - **Grok Build (xAI `grok`)**: `~/.grok/sessions/<percent-encoded-cwd>/<session-uuid>/` — `updates.jsonl` (authoritative ACP session-update stream) with `summary.json` metadata and `chat_history.jsonl` fallback (override the base dir with `GROK_HOME`). Resume with `grok --resume <session-id>`.
- - **Codebuff / Freebuff (`codebuff`)**: `~/.config/manicode/projects/<project>/chats/<chat-id>/chat-messages.json` with its `run-state.json` (override with `CASS_CODEBUFF_DATA_ROOT`). Both products write the same Manicode store and no chat records which binary wrote it, so their sessions share one lineage identity, `codebuff` (filter with `--agent codebuff`). Messages are reconciled by their native IDs, so an edited message updates in place instead of duplicating.
- - **Kiro CLI (`kiro`)**: `~/.kiro/sessions/cli/<session-uuid>.jsonl` (append-only event log: prompts, assistant messages, tool results) with the matching `<session-uuid>.json` snapshot read for session ID, working directory, title, timestamps and model.
- - **Continue (`continue`)**: `~/.continue/sessions/<id>.json`, one JSON snapshot per session holding its current ordered history (IDE extension and CLI). `CONTINUE_GLOBAL_DIR` moves the store, as it does for Continue itself.
- Claude Code Desktop sidecars preserve title, workspace, model, and session IDs,
- but not necessarily the full conversation body. If Claude Code has culled an old
- CLI JSONL body, cass can still index searchable sidecar metadata while reporting
- that the conversation body is unavailable.
- #### Connector Details
- **Pi-Agent** parses JSONL session files with rich event structure:
- - **Location**: `~/.pi/agent/sessions/` (override the agent home with `PI_CODING_AGENT_DIR`, or the sessions directory directly with `PI_SESSIONS_DIR`)
- - **Format**: Typed events—`session_start`, `message`, `model_change`, `thinking_level_change`
- - **Features**: Extracts extended thinking content, flattens tool calls with arguments, tracks model changes
- - **Detection**: Scans for `*_*.jsonl` pattern in sessions directory
- **Oh My Pi (`omp`)** uses the same pi-family wire format but remains a separate
- agent identity throughout search, analytics, resume, TUI, and HTML export:
- - **Default and profiles**: `~/.omp/agent/sessions/` and `~/.omp/profiles/<name>/agent/sessions/`; `OMP_PROFILE` selects a profile and takes precedence over legacy `PI_PROFILE`
- - **XDG**: `$XDG_DATA_HOME/omp/sessions/` and `$XDG_DATA_HOME/omp/profiles/<name>/sessions/` when the OMP XDG root exists
- - **Overrides and ownership**: `PI_CODING_AGENT_SESSION_DIR` names the exact OMP sessions directory. `CASS_OMP_DATA_ROOT` declares an OMP-only archive/store root and is the right choice for copied, mounted, or custom OMP data. `PI_CODING_AGENT_DIR` is shared by both pi-family programs, so CASS conservatively keeps otherwise-ambiguous paths under that root owned by Pi-Agent; use one of the OMP-specific variables when OMP identity matters. `PI_CONFIG_DIR` changes the home-relative `.omp` config directory name.
- - **Resume**: results in the current live home/config store use `omp [--profile <name>] --resume <id>`; copied profiles, XDG archives, remote mirrors, and explicit roots also carry `--session-dir <dir>` so a canonical-looking archive cannot reopen a different live store
- - **Upgrade behavior**: archives created by older cass versions are reclassified from `pi_agent` to `omp` using the same conservative canonical/XDG/remote-mirror ownership policy as live discovery, then the derived lexical index and analytics are rebuilt so a transcript cannot remain attributed to both agents. The conventional `~/.local/share/omp` shape is durable path evidence; an arbitrary historical custom `$XDG_DATA_HOME/omp` path is reclassified only while that root is currently configured and resolvable. Without provider-qualified evidence, ambiguous historical paths fail closed as Pi-Agent rather than letting a generic `.../omp/sessions` directory steal ownership.
- **OpenCode** reads SQLite databases from workspace directories:
- - **Location**: `.opencode/` directories (scans recursively from home)
- - **Format**: SQLite database with sessions table
- - **Detection**: Finds directories named `.opencode` containing database files
- ### 🌐 Remote Sources (Multi-Machine Search)
- Search across agent sessions from multiple machines—your laptop, desktop, and remote servers—all from a single unified index. `cass` uses SSH/rsync to efficiently sync session data, tracking provenance so you know where each conversation originated.
- #### Interactive Setup Wizard (Recommended)
- The easiest way to configure multi-machine search is the interactive setup wizard:
- ```bash
- cass sources setup
- ```
- **What the wizard does:**
- 1. **Discovers** SSH hosts from your `~/.ssh/config`
- 2. **Probes** each host to check for:
- - Existing cass installation (and version)
- - Agent session data (Claude, Codex, Cursor, Gemini, etc.)
- - System resources (disk space, memory)
- 3. **Lets you select** which hosts to configure
- 4. **Installs cass** on remotes that don't have it (optional)
- 5. **Indexes** existing sessions on remotes (optional)
- 6. **Configures** `sources.toml` with correct paths and mappings
- 7. **Syncs** the configured remotes by running `cass sources sync` right after configuration (skipped with `--skip-sync` or `--dry-run`; `--json` setup defers it and reports the command to run)
- **Wizard options:**
- | Flag | Purpose |
- |------|---------|
- | `--hosts <names>` | Configure only specific hosts (comma-separated) |
- | `--dry-run` | Preview changes without applying them |
- | `--non-interactive` | Use auto-detected defaults for scripting |
- | `--skip-install` | Don't install cass on remotes |
- | `--skip-index` | Don't run indexing on remotes |
- | `--skip-sync` | Skip the final `cass sources sync`. Interactive setup runs that sync after the hosts are configured and records it as complete only once it has actually finished; `--json` setup always defers it and reports `sync.status = "pending"` with the command to run |
- | `--resume` | Resume an interrupted setup |
- | `--json` | Output progress as JSON (for automation) |
- **Examples:**
- ```bash
- # Full interactive wizard
- cass sources setup
- # Configure specific hosts only
- cass sources setup --hosts laptop,workstation,build-server
- # Preview without making changes
- cass sources setup --dry-run
- # Resume interrupted setup
- cass sources setup --resume
- # Non-interactive for CI/CD
- cass sources setup --non-interactive --hosts myserver --skip-install
- ```
- **Resumable state:** If setup is interrupted (Ctrl+C, connection lost), state is saved to the cache directory (`~/.cache/cass/setup_state.json` on Linux). Resume with `--resume`.
- #### Testing your real fleet
- Tailscale discovery is optional: `cass sources discover --tailscale --json` adds
- online tailnet peers to SSH-config discovery, and `cass sources setup --tailscale`
- offers them in setup. It reads local `tailscale status --json` with a five-second
- deadline; a missing CLI, stopped daemon, or login failure produces a warning and
- leaves SSH-config discovery available. Explicit `setup --hosts` skips discovery.
- Connections use ordinary SSH over assigned Tailscale IPv4 addresses, so MagicDNS
- is not required. Matching SSH aliases retain their user/key configuration;
- otherwise SSH uses its normal defaults. IPv6-only peers are currently omitted.
- Tailscale ACLs, SSH authorization and host-key checks still apply; discovery does
- not log in, install Tailscale, or change either SSH or tailnet configuration.
- The local fixture and Docker tests do not prove that your machines can sync and
- search each other's sessions. The opt-in live harness uses actual SSH connections
- and `cass sources discover`, `sources add`, `sources sync`, and `search`. It creates isolated synthetic
- Codex sessions on each machine, checks source provenance and filters, repeats a
- sync to detect duplicates, and appends messages. It checks both lexical and default
- hybrid search, requires one JSON response per sync, holds the real indexing lock to
- test busy refusal, and recovers transferred sessions through `sources reingest`.
- A refused SSH connection must leave the other sources searchable.
- Keep the inventory and SSH configuration **outside this repository**. For example,
- create a mode-0600 JSON file containing:
- ```json
- {
- "ssh_config": "/private/path/to/ssh_config",
- "hosts": [{"ssh": "workstation"}, {"ssh": "laptop"}]
- }
- ```
- Then run with an explicit binary:
- ```bash
- python3 scripts/e2e/live_fleet_search.py \
- --inventory /private/path/to/fleet.json \
- --cass-bin /path/to/cass
- ```
- Python 3 and authenticated SSH access are required on the remote machines.
- The Unix runner needs Python 3.9+, rsync, and a CASS binary supporting the tested
- commands. Each inventory alias must appear in the supplied SSH configuration;
- included configuration files are supported. Host-key verification stays enabled.
- To exercise actual tailnet discovery and transport, add `--tailscale` to the
- harness command and use tailnet IPv4 addresses as the private inventory targets.
- Keep any required SSH users, keys and trusted host-key aliases in the private SSH
- configuration. For a discovery test independent of explicit aliases, use SSH
- `Match originalhost` entries rather than literal `Host` entries for those addresses.
- The harness retains fresh test directories and raw
- receipts privately outside git; it never changes existing session archives or
- deletes test data. Console results use ordinal labels. An unreachable machine
- keeps the overall result failed, even if the other machines pass. Do not attach
- raw receipts or inventories to public issues: they contain machine identities.
- #### Remote Installation Methods
- When the wizard installs `cass` on remote machines, it tries every viable method in this priority order, falling through to the next when one fails; setup fails only when all of them do, and the error lists each attempt:
- | Priority | Method | Speed | Requirements |
- |----------|--------|-------|--------------|
- | 1 | **Pre-built binary** | ~10s | curl/wget, GitHub access, compatible release binary |
- | 2 | **Source build** | ~30 min | rustup and cargo, curl/wget, 6GB free disk in `$HOME`, 10GB RAM |
- | 3 | **Full bootstrap** | ~30 min | curl, 6GB free disk in `$HOME`, 10GB RAM (installs rustup, then builds as in 2) |
- The source build does what `install.sh --from-source` does: it downloads the
- release tag's source archive into `$HOME`, installs the Rust toolchain that
- tag's `rust-toolchain.toml` pins (a dated nightly; cass does not build on
- stable), and runs `cargo install --locked --path . --bin cass` inside it, so the
- binary lands in `~/.cargo/bin/cass`. The unpacked tree is removed afterwards. It
- does not use crates.io. It builds with thin LTO instead of the release
- profile's fat LTO, so the binary is somewhat larger and slower than the
- published one. Measured building v0.10.0 on a fresh account (two build jobs):
- 28 minutes, 8.6 GB peak compiler memory (10.9 GB and 36 minutes with fat LTO),
- 1.5 GB toolchain, 0.8 GB cargo cache and a 2.6 GB build tree. The wizard
- offers it only to hosts above those floors.
- > **crates.io lags the releases:** the newest version on crates.io is 0.7.0
- > (2026-08-25), so `cargo install coding-agent-search` builds 0.7.0. Later
- > versions depend on `franken-agent-detection` and `frankensearch` at exact git
- > revisions. Their required APIs must be published before CASS can return to
- > registry-only dependencies (bead zztql; GH #548). Use the installer or the
- > GitHub Release binaries for a
- > current version.
- **Resource Requirements**:
- - Minimum 1GB free disk in `$HOME` for the pre-built binary
- - 6GB free disk in `$HOME` and 10GB RAM for a source build
- - Linux pre-built binaries require glibc 2.28+ on conventional FHS-style distributions (see *System Requirements*); older glibc, musl-only, and NixOS hosts fall back to source installation when possible.
- - SSH access with key-based authentication
- **What Gets Installed**:
- - The `cass` binary (location depends on method: `~/.cargo/bin/cass` for cargo-based, `~/.local/bin/cass` for pre-built binary)
- - No daemon, no background services—just the binary
- **Installation Progress**: The wizard shows real-time progress for each stage:
- ```
- Installing cass on laptop...
- [1/4] Checking environment... ✓
- [2/4] Downloading binary... ████████░░ 80%
- [3/4] Verifying checksum... ✓
- [4/4] Setting up PATH... ✓
- ```
- Use `--skip-install` if you prefer to install manually on remotes.
- #### Host Discovery & Probing
- The setup wizard automatically discovers SSH hosts from your configuration:
- **Discovery Sources**:
- - `~/.ssh/config` (parses Host entries)
- - Hosts with wildcards (`*`, `?`) are automatically excluded
- **Probe Results** (for each discovered host):
- | Check | Purpose |
- |-------|---------|
- | **Connectivity** | Can we establish SSH connection? |
- | **cass Version** | Is cass already installed? What version? |
- | **Agent Data** | Which agents have session data? |
- | **Session Count** | How many conversations exist? |
- | **System Info** | OS, architecture, disk space, memory |
- Each setup run probes every selected host afresh; probe results are not cached between runs.
- #### Manual Setup
- For manual configuration without the wizard:
- ```bash
- # Add a remote machine using platform presets
- cass sources add user@laptop.local --preset macos-defaults
- # Or specify paths explicitly
- cass sources add dev@workstation --path ~/.claude/projects --path ~/.codex/sessions
- # Sync sessions from all configured sources
- cass sources sync
- # Check source health and connectivity
- cass sources doctor
- ```
- #### Remote Archive Safety
- Remote source diagnostics are intentionally local-only. `cass triage --json`,
- `cass doctor --json`, `cass health --json`, and `cass status --json` report the
- `remote_source_sync` summary from cass-owned evidence: `sources.toml`,
- `sync_status.json`, the local `remotes/<source>/mirror/` copy, and archive DB
- provenance rows. They do not open SSH sessions, mutate remote machines, or
- rewrite provider session logs while classifying source gaps.
- `cass sources doctor` is the explicit networked exception: it performs bounded,
- read-only probes of configured source hosts. Its per-source human summary keeps
- the same native reachability, binary-health, and mirror/sync state codes and
- safe command as the JSON report. It intentionally does not claim local search
- readiness, because a remote host probe cannot establish the controller's local
- SQLite, lexical, or semantic asset state.
- This matters because agent harnesses can prune their own logs. If a laptop is
- retired, a remote path disappears, or a provider truncates older sessions, the
- cass archive DB and cass-owned local mirror may be the only remaining evidence
- for those conversations. Treat gap names such as `remote_source_unavailable`,
- `remote_source_pruned`, `local_archive_ahead_of_remote`, and
- `remote_copy_ahead_verified` as preservation signals first: keep the archive and
- mirror intact, then run the recommended `cass sources sync --json` (all configured remote sources; `--source <name>` narrows it) or
- source-specific sync command after reviewing the reported evidence.
- Raw-mirror retention is explicit and audited. Use `cass mirror prune
- --older-than 90d --json` or `cass mirror prune --max-size 100GB --json` to get a
- dry-run plan; add `--apply` only after reviewing the scope and totals. Preview
- `entries` contain at most 1,000 manifest/blob details; `omitted_entry_count`
- reports additional candidates. Planned counts and bytes cover the entire plan,
- including omitted details. Use provider/path selectors to inspect a narrower
- scope. Previews do not append audit records. Add
- `--keep-tag <tag>` to pin captures linked to tagged conversations. `prune`
- holds down blobs referenced by captures from the last 7 days by default, writes
- complete intent/result records to `raw-mirror/v1/pruned.jsonl` for non-empty
- applied plans, and refuses apply mode
- while an index/watch job is active.
- Applied pruning syncs the audit independently of the optional capture setting
- `CASS_RAW_MIRROR_FSYNC`. Each completed result is recorded before the next
- removal; a later failure preserves those earlier results. An abrupt crash
- between a removal and its result record can still leave an intent without a
- confirmed result.
- Use `--provider opencode` and/or `--source-path '*/opencode.db'` with an age
- or size rule to target one source without retiring unrelated captures.
- Repeated providers are alternatives; a source-path glob further narrows them.
- `--keep-latest N` retires every capture of a source file except its newest N
- (a source file is one provider, source and original path) and keeps those N
- out of reach of `--older-than` and `--max-size`. Use it for a prune that runs
- on a timer: `cass mirror prune --keep-latest 1 --safety-hold-down 6h --apply`
- keeps the mirror to the newest capture of each source file plus whatever was
- captured inside the hold-down window, and never retires the only copy of a
- session whose provider has since deleted it. Older captures of an appended
- transcript share their complete chunks with the newest one, so retiring them
- frees only their superseded tail chunks; for a file that was rewritten rather
- than appended to, it also drops the earlier versions.
- A capture stages its copy under `raw-mirror/v1/tmp/capture.<pid>.<ts>.<n>` and
- holds the mirror lock until it publishes. A capture that is killed, for example
- by a `timeout` around `cass index`, leaves that directory behind. An unscoped
- `cass mirror prune` (no `--provider` or `--source-path`) takes the same lock, so
- any staging directory it finds is abandoned. The preview lists each one that
- has not been written for an hour, with its size, as a `staging` entry, and
- `--apply` removes it. Staging-named symlinks are not followed.
- A pruned capture of a source that is still on disk is copied again by the next
- index run. On a machine whose providers never delete their session files, set
- `CASS_RAW_MIRROR=0` (or `false`, `no`, `off`) to stop capturing altogether.
- Indexing and search are unchanged, and existing captures stay until you prune
- them. `cass doctor` reports `raw_mirror_capture_disabled` and warns about what is
- given up: a session file its provider later deletes survives only in the
- archive DB.
- With a selector, `--max-size` measures unique blobs in that selection. Shared
- blobs still referenced outside it and orphan blobs without source provenance
- remain protected. The JSON plan records the selectors and `scope_blob_bytes`.
- Large mutable sources are stored as content-addressed chunks: JSONL and
- NDJSON transcripts of 256 KiB or more in 256 KiB chunks, and other sources of
- 8 MiB or more, such as SQLite stores, in 4 MiB chunks. A growing transcript
- reuses every unchanged complete chunk, so an index run after an append stores
- only its changed tail chunk and a manifest, and SQLite sources reuse unchanged
- 4 MiB byte regions. Each historical snapshot remains byte-exact without
- writing another full-file blob. Existing whole-blob manifests remain readable;
- `cass doctor --json` reports `storage_kind`, `chunk_count`, the full-source
- digest, and verifies every referenced chunk before treating a snapshot as
- recovery authority.
- #### Configuration File
- Sources are configured in the platform config directory (Linux: `~/.config/cass/sources.toml`, macOS: `~/Library/Application Support/cass/sources.toml`):
- ```toml
- [[sources]]
- name = "laptop"
- type = "ssh"
- host = "user@laptop.local"
- paths = ["~/.claude/projects", "~/.codex/sessions"]
- sync_schedule = "manual"
- [[sources]]
- name = "workstation"
- type = "ssh"
- host = "dev@work.example.com"
- paths = ["~/.claude/projects"]
- sync_schedule = "daily"
- # Path mappings rewrite remote paths to local equivalents
- [[sources.path_mappings]]
- from = "/home/dev/projects"
- to = "/Users/me/projects"
- # Agent-specific mappings
- [[sources.path_mappings]]
- from = "/opt/work"
- to = "/Volumes/Work"
- agents = ["claude_code"]
- ```
- **Configuration Fields:**
- | Field | Description |
- |-------|-------------|
- | `name` | Friendly identifier (becomes `source_id`) |
- | `type` | Connection type: `ssh` or `local` |
- | `host` | SSH host (`user@hostname`) |
- | `paths` | Paths to sync (supports `~` expansion) |
- | `sync_schedule` | `manual`, `hourly`, or `daily`. Only the jobs installed by `cass schedule install` run it; without them it is a label and syncs happen when you run `cass sources sync` |
- | `path_mappings` | Rewrite remote paths to local equivalents |
- #### CLI Commands
- ```bash
- # List configured sources
- cass sources list [--verbose] [--json]
- # Add a new source
- cass sources add <user@host> [--name <name>] [--preset macos-defaults|linux-defaults] [--path <path>...] [--no-test] [--json]
- # Set how often `cass schedule install` jobs sync a remote source (default: manual)
- cass sources schedule <name> <manual|hourly|daily> [--json]
- # Remove a source
- cass sources remove <name> [--purge] [-y]
- # Check connectivity and config
- cass sources doctor [--source <name>] [--json]
- # Sync sessions
- cass sources sync [--source <name>] [--no-index] [--verbose] [--dry-run] [--json]
- ```
- #### Read-Only (rrsync) Remotes
- A key restricted in the remote's `authorized_keys` to `command="rrsync -ro /home/user",restrict` works: `cass sources sync` retries without `--secluded-args` (which rrsync refuses), and the connectivity check in `sources add` and `sources doctor` runs `true`, the one non-rsync command rrsync allows. Three things differ from an unrestricted key:
- - Write remote paths without `~`. cass expands `~` by asking the remote shell for `$HOME`, and rrsync refuses that.
- - rrsync anchors every path at its directory. With `rrsync -ro /home/user`, configure `/.claude/projects` (served as `/home/user/.claude/projects`); `/home/user/.claude/projects` would be served as `/home/user/home/user/.claude/projects`. Paths containing `..` are refused.
- - Tailscale SSH authenticates through the tailnet, not `authorized_keys`, so a forced command does not restrict a Tailscale SSH session. Use a regular sshd for a read-only key.
- #### Excluding Noisy Agent Harnesses
- If one harness is generating mostly junk or looped output, you can disable it persistently even if its files remain on disk:
- ```bash
- # Inspect current include/exclude state
- cass sources agents list --json
- # Stop indexing this harness in future runs
- cass sources agents exclude openclaw
- # Re-enable it later
- cass sources agents include openclaw
- ```
- `cass` stores this preference in `sources.toml` (`~/.config/cass/sources.toml` on Linux, `~/Library/Application Support/cass/sources.toml` on macOS). New scans, syncs, and watcher processes read the saved exclusion.
- By default, `cass sources agents exclude <agent>` also removes already archived local data for that agent and rebuilds the lexical index so the exclusion frees space instead of only blocking future imports.
- A purging exclusion requires exclusive access to the selected archive and search data. If an indexer, watcher, or maintenance operation already holds that access, the command exits with code 7 and leaves configuration and archive data unchanged. Stop the active process, then retry the exclusion. Once admitted, the command retains exclusive access through deletion and publication of the rebuilt lexical index.
- Exclusions apply to a whole connector. Excluding `openclaw` also removes archived conversations for named agents such as `openclaw/alice` and `openclaw/bob`. Qualified names such as `openclaw/alice` are rejected by `exclude`; they are never silently widened to the whole connector. Use `cass forget --agent openclaw/alice` to preview removing only that named agent's archived conversations, then add `--apply` to confirm the deletion.
- If you want to block future indexing but keep the data already archived:
- ```bash
- cass sources agents exclude openclaw --keep-indexed-data
- ```
- This option saves only the configuration change and can run while indexing is active. Restart any running watcher for the new exclusion to take effect; its current selection of connectors remains active until it exits.
- #### Sync Engine Internals
- The sync engine uses rsync over SSH for efficient delta transfers and falls back to other transports when rsync is unavailable:
- **Transfer Methods** (auto-detected):
- | Method | When Used | Characteristics |
- |--------|-----------|-----------------|
- | **rsync** | rsync available on both ends | Delta transfers, compression, progress stats |
- | **WSL rsync** | Windows without native rsync, WSL with rsync installed | Runs `wsl rsync` |
- | **scp** | rsync unavailable | Full file copies through the system `scp`, inheriting the OpenSSH agent, keys and `~/.ssh/config` |
- | **SFTP** | the fallbacks above unavailable | Full file transfers via the SSH native protocol |
- **Safety Guarantees**:
- - **Additive-only syncs**: rsync runs WITHOUT `--delete`, so remote deletions never propagate locally.
- - **Local copies follow the remote**: rsync runs with `-a` and without `-u`, so a local mirror file that differs from the remote is overwritten, even when the local copy is newer. The mirror is a copy of the remote, not a place to edit sessions.
- - **Interrupted transfers resume**: `--partial` keeps a partly transferred file under its final name so the next sync continues it. A failed sync can therefore leave a truncated file until the next sync completes.
- **Transfer Configuration**:
- | Setting | Default | Purpose |
- |---------|---------|---------|
- | Connection timeout | 10s | Fail fast on unreachable hosts |
- | Transfer timeout | 300 s of I/O inactivity | rsync `--timeout` aborts a transfer that stalls this long; there is no wall-clock limit on a transfer that keeps moving |
- | Compression | Enabled | Reduce bandwidth for text-heavy sessions |
- | Partial transfers | Enabled | Resume interrupted syncs |
- **rsync Flags Used**:
- ```
- -avz --links --safe-links --stats --partial [--protect-args | --secluded-args] --timeout 300 \
- -e "ssh [-F $CASS_SSH_CONFIG] -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=yes"
- ```
- Where `-avz` = archive mode + verbose + compression. `--protect-args`/`--secluded-args` is auto-detected per remote rsync version (omitted when the remote rejects it), and `--timeout` carries the transfer timeout in seconds. `StrictHostKeyChecking=yes` means a host whose key is not already in `known_hosts` fails with "Host key verification failed". Connect once with plain `ssh <host>` and accept the key, or add it with `ssh-keyscan`, before the first sync.
- **Data Flow**:
- ```
- Remote: ~/.claude/projects/
- ↓ (rsync over SSH)
- Local: ~/.local/share/coding-agent-search/remotes/<source>/mirror/<path>_<hash>/
- ↓ (connector scan)
- Index: agent_search.db + index/v9-quill/
- ```
- Where `<path>` is a filesystem-safe version of the remote path (e.g. `.claude_projects`), and `<hash>` is an FNV-1a hash of the original path in hex, so `foo/bar` and `foo_bar` never collide.
- Sessions from remotes are indexed alongside local sessions, with provenance tracking to identify origin.
- #### Path Mappings
- When viewing sessions from remote machines, workspace paths may not exist locally. Path mappings rewrite these paths so file links work on your local machine:
- ```bash
- # List current mappings
- cass sources mappings list laptop
- # Add a mapping
- cass sources mappings add laptop --from /home/user/projects --to /Users/me/projects
- # Test how a path would be rewritten
- cass sources mappings test laptop /home/user/projects/myapp/src/main.rs
- # Output: /Users/me/projects/myapp/src/main.rs
- # Agent-specific mappings (only apply for certain agents)
- cass sources mappings add laptop --from /opt/work --to /Volumes/Work --agents claude_code,codex
- # Remove a mapping by index
- cass sources mappings remove laptop 0
- ```
- #### TUI Source Filtering
- In the TUI, filter sessions by origin:
- - **F11**: Cycle source filter (all → local → remote → all)
- - **Shift+F11**: Open source filter menu to select specific sources
- Remote sessions display with a source indicator (e.g., `[laptop]`) in the results list.
- #### Provenance Tracking
- Each conversation tracks its origin:
- - `source_id`: Machine identifier (e.g., "laptop", "workstation")
- - `origin_kind`: `local` or `remote`
- - `origin_host`: the remote host label, absent for local sessions
- - `workspace_original`: Original path on the remote machine (before path mapping)
- `--fields provenance` selects exactly `source_id`, `origin_kind` and `origin_host`.
- These fields appear in JSON/robot output and enable filtering:
- ```bash
- cass search "auth error" --source laptop --json
- cass timeline --since 7d --source remote
- cass stats --by-source
- ```
- ## 🤖 AI / Automation Mode
- `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:
- ```bash
- # 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 -robot --limit=5` | `cass --robot --limit=5` | Single-dash long flags normalized |
- | `cass --Robot --LIMIT 5` | `cass --robot --limit 5` | Case normalized |
- | `cass search "auth" --max_results 5` | `cass search "auth" --limit 5` | Snake-case long flag normalized before alias recovery |
- | `cass find "auth"` | `cass search "auth"` | `find`/`query`/`q` → `search` via alias table |
- | `cass --robot-docs` | `cass robot-docs` | Flag-as-subcommand detected |
- | `cass commands --json` | `cass robot-docs commands` | Robot-docs topic shorthand detected |
- | `cass schemas --json` | `cass robot-docs schemas` | Robot-docs topic shorthand detected |
- | `cass ready --json` | `cass triage --json` | One-shot triage alias |
- | `cass preflight --json` | `cass triage --json` | One-shot triage alias |
- | `cass --json` | `cass triage --json` | Top-level robot request defaults to safe preflight |
- | `cass --robot` | `cass triage --json` | Top-level robot request defaults to safe preflight |
- | `cass --json search "auth"` | `cass search "auth" --json` | Leading structured flag moved to the robot-capable subcommand |
- | `cass --robot status` | `cass status --json` | Leading robot flag canonicalized to JSON output |
- | `cass answer "auth" --json` | `cass pack "auth" --json` | Cited-handoff aliases normalized to answer pack |
- | `cass why auth failed --json --max-evidence 3` | `cass pack "auth failed" --json --max-evidence 3` | Question/RC prompt aliases normalized to answer pack |
- | `cass auth failed --json --max-evidence 3` | `cass pack "auth failed" --json --max-evidence 3` | Bare robot queries with pack-only flags become answer packs |
- | `cass search auth failed --json --max-evidence 3` | `cass pack "auth failed" --json --max-evidence 3` | Explicit robot search with pack-only flags becomes an answer pack |
- | `cass html-export session.jsonl --json` | `cass export-html session.jsonl --json` | Reversed HTML export aliases normalized to the archive exporter |
- | `cass current --json` | `cass sessions --current --json` | Current-session shorthand normalized to session discovery |
- | `cass sessions current --json` | `cass sessions --current --json` | Positional `current` accepted as the sessions current flag |
- | `cass search --query "auth" --json` | `cass search "auth" --json` | Named query option converted to required positional query |
- | `cass search --q "auth" --json` | `cass search "auth" --json` | Short/familiar query aliases converted to required positional query |
- | `cass search auth error --json` | `cass search "auth error" --json` | Adjacent unquoted query words folded into one search |
- | `cass auth error --json` | `cass search "auth error" --json` | Unquoted robot-mode query words folded into search |
- | `cass search --agent codex --limit 5 auth error --json` | `cass search "auth error" --agent codex --limit 5 --json` | Query moved before leading search filters |
- | `cass view --path session.jsonl --line 42 --json` | `cass view session.jsonl --line 42 --json` | Named path option converted to required positional path |
- | `cass view session.jsonl --line-number 42 --json` | `cass view session.jsonl --line 42 --json` | Legacy alias for `--line`; still reads raw file line 42 |
- | `cass view session.jsonl line_number=42 --json` | `cass view session.jsonl --message-index 42 --json` | 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 --json` | `cass view session.jsonl --source local --message-index 42 --json` | Search hit field bundle accepted as a follow-up command (add `conversation_id` when the file holds several conversations) |
- | `cass search "auth" --format json` | `cass search "auth" --robot-format json` | Familiar format spelling converted to robot format |
- | `cass search "auth" --output json` | `cass search "auth" --robot-format json` | Familiar output spelling converted to robot format |
- | `cass help search --json` | `cass robot-docs commands` | Structured help intent routed to the machine-readable command reference |
- | `cass --format json status` | `cass status --robot-format json` | Leading format request moved to the target subcommand |
- | `cass search "auth" --max-results 5` | `cass search "auth" --limit 5` | Result-count alias converted to canonical limit |
- | `cass search "auth" -n 5` | `cass search "auth" --limit 5` | Familiar short count flag converted to canonical limit |
- | `cass search "auth" --last 7 --before now` | `cass search "auth" --since -7d --until now` | Familiar time-window aliases converted to canonical filters |
- | `cass search "auth" last=7d before=now` | `cass search "auth" --since -7d --until now` | Bare time-window assignments converted to canonical filters |
- | `cass search "auth" --provider codex` | `cass search "auth" --agent codex` | Provider/tool/connector aliases converted to canonical agent filter |
- | `cass search "auth" provider=codex` | `cass search "auth" --agent codex` | Bare provider assignment converted to canonical agent filter |
- | `cass search auth provider codex limit 5` | `cass search auth --agent codex --limit 5` | Bare filter key/value pairs after a query converted to canonical flags |
- | `cass search --limt 5` | `cass search --limit 5` | Flag typos within Levenshtein distance ≤2 corrected |
- The CLI applies multiple normalization layers:
- 1. **Typo correction**: when parsing fails, long flag names within Levenshtein distance 2 of a known flag are corrected (e.g. `--limt` → `--limit`), and a first word within distance 2 of a subcommand is corrected to it (e.g. `serach` → `search`). A word that already names a subcommand is never changed, so `cass status --jsn` runs `status --json`. `forget` and `upgrade` are reached only by exact spelling.
- 2. **Case normalization**: `--Robot`, `--LIMIT` → `--robot`, `--limit`
- 3. **Snake-case flag recovery**: `--max_results`, `--data_dir`, and other known snake_case long flags become canonical kebab-case before alias recovery runs
- 4. **Single-dash recovery**: `-robot` → `--robot` (common LLM mistake)
- 5. **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`
- 6. **Robot-docs topic shorthands**: non-command topics such as `commands`, `schemas`, `examples`, `exit-codes`, and `quickstart` become `robot-docs <topic>` instead of falling through to search; command topics such as `doctor` and `sources` use structured help (`cass help doctor --json`, `cass sources --help --json`). Bare `cass guide` is reserved for the guided-operations planner; use `cass robot-docs guide` for the robot-docs walkthrough.
- 7. **Root robot default**: `cass --json`, `cass --robot`, or `cass --robot-format json` with no subcommand runs read-only `triage`
- 8. **Leading structured flag recovery**: `--json`/`--robot` before a robot-capable subcommand is moved onto that subcommand
- 9. **Named positional recovery**: `--query`/`--q`/`--text`/`--pattern` for search/pack and `--path`/`--source-path`/`--file`/`--session` for drill-down/export commands become the required positional argument
- 10. **Multi-word query recovery**: adjacent unquoted query words after `search`/`pack` become one query positional
- 11. **Structured format recovery**: `--format json|jsonl|compact|sessions|toon`, `--output json|jsonl|compact|sessions|toon`, and `--output-format ...` are accepted as `--robot-format ...` on robot-capable commands; `export --format ...` and `export --output <file>` keep their export meanings
- 12. **Structured help recovery**: `help --json`, `help commands --json`, and `search --help --json` route to `robot-docs guide` / `robot-docs commands`; plain `--help` stays native clap help
- 13. **Result-count aliases**: `--max-results`, `--num-results`, `--results`, `--count`, `--top-k`, and `-n` become `--limit` on commands with result limits
- 14. **Time-window aliases**: `--last 7`, `--before now`, `last=7d`, and `before=now` become canonical `--since`/`--until` filters
- 15. **Provider aliases**: `--provider`, `--tool`, `--connector`, and matching assignments become canonical `--agent` filters on search-like commands
- 16. **Bare option pairs**: after at least one search/pack query word, `provider codex`, `limit 5`, and `last 7d` become canonical filter flags before the remaining words are folded into the query
- 17. **Pack-intent recovery**: a bare robot query or explicit structured-output `search` with pack-only flags such as `--max-evidence`, `--max-sessions`, or `--freshness-policy` becomes `pack`, not implicit or explicit `search`
- 18. **Drill-down line aliases**: `--line-number`, `--line_number` and `line=42` become `--line` (a raw file line)
- 19. **Search-hit fields**: `line_number=42` pasted from a search hit becomes `--message-index 42` (the canonical message ordinal the hit names), and a `source_path=... source_id=... line_number=...` bundle becomes the canonical path, `--source` and `--message-index` form for follow-up `view`/`expand` commands
- 20. **Leading-filter query recovery**: if a search/pack query comes after leading options, the query is moved back to the required positional slot
- 21. **Implicit robot search**: unquoted top-level words with an explicit robot/JSON output request become a `search` query unless they look like a subcommand typo
- 22. **Current-session shorthand**: `current`, `current-session`, and `sessions current` become `sessions --current`
- 23. **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: auto-corrected: <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 `--robot-meta`.
- ### Structured Output Formats
- Every command supports machine-readable output:
- ```bash
- # 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.
- ```bash
- # 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
- `export-html` when you need a full browsable session archive; packs are
- token-budgeted evidence bundles, not full exports and not external
- summarization.
- 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 `--include-skill-content`
- 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:
- ```bash
- # 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 work-packet`, `swarm lint`, `swarm evidence`,
- `swarm proof-debt` and `swarm failure-patterns` 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 --no-db` (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 --json` (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
- `agent-mail-unavailable` advisory whenever Agent Mail messages are not
- collected. Fixture selection (`--fixture <file>` or `--fixture-dir <dir>
- --fixture-id <id>`) retains deterministic behavior; `swarm dependency-drift`
- 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 dependency-drift` 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" --robot` 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 |
- |------|--------|
- | `--fields minimal` | Only `source_path`, `line_number`, `agent`, `source_id`, `conversation_id` |
- | `--fields summary` | `minimal` plus `title`, `score` |
- | `--fields score,title,snippet` | Custom field selection |
- | `--max-content-length 500` | Truncate long fields (UTF-8 safe, adds "...") |
- | `--max-tokens 2000` | Soft budget (~4 chars/token); adjusts truncation dynamically |
- | `--limit 5` | Cap number of results |
- | `cass pack "query" --robot` | Build a cited handoff pack from selected search evidence |
- | `pack --max-tokens N` | Set the pack planner's soft budget |
- | `pack --max-evidence N` | Cap evidence items selected into the pack |
- | `pack --max-sessions N` | Limit how many sessions can contribute evidence |
- | `pack --max-excerpt-chars N` | Shorten each cited excerpt before token estimation |
- | `pack --fields summary` | Return top-level summary fields for a smaller JSON envelope |
- | `pack --field-mask minimal\|standard\|full` | Select a documented pack projection; `--fields` accepts the same presets |
- | `pack --freshness-policy strict --freshness-window-seconds N` | Reject stale evidence instead of silently mixing it into a pack |
- | `pack --sessions-from FILE` | 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:
- ```bash
- 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 --robot` against a fresh data dir:
- ```json
- {
- "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. `missing-index`, `missing-db`, `semantic-unavailable`, `embedder-unavailable`, `ambiguous-source`, `timeout`, `config`, `lock-busy`). 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 --full` |
- | 2 | Usage error | Fix syntax (hint provided) |
- | 3 | Index/DB missing | Run `cass index --full` (retryable: true) |
- | 4 | I/O failure or unsafe operation refused (not a network code) | Branch on `err.kind`: fix path/permissions/space for `io`/`output-not-writable`; follow the hint for `refused-unsafe` |
- | 5 | Data corruption, or maintenance required | Inspect `cass health --json` / `cass status --json` / `cass doctor --json` and follow `recommended_action`: usually rebuild derived assets (`maintenance-required`, `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. `--password-stdin`) 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 `--mode lexical` |
- | 20-21 | Model acquisition | Check `err.kind`, `err.hint` |
- | 22 | I/O during model handling | Retry |
- | 23 | Model download | Retry or use `--from-file` |
- | 24 | I/O during model verify/install | Retry |
- | 70 | `cass index` stalled and aborted (kind `index-stalled` envelope on stderr) | Inspect `cass status --json`, then rerun `cass index` |
- | 130 | Interrupted (SIGINT) | Rerun; `cass sources setup --resume` continues an interrupted setup |
- 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 `--robot-format sessions` instead fails with exit 10, kind `timeout`. Explicit `--mode semantic` is the other exception: when the remaining budget cannot admit semantic setup or dispatch, search fails with exit 10, kind `timeout`, `retryable: true`, and a `semantic_budget checkpoint=...` message, 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 --full --force-rebuild`. 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:
- ```bash
- # 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 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
- ```
- ### Aggregation & Analytics
- Aggregate search results server-side to get counts and distributions without transferring full result data:
- ```bash
- # 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**:
- ```json
- {
- "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:
- ```bash
- 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 `--db` path plus `--conversation-id`, 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. `--budget-ms` 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;
- `--max-sessions` 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 `message-fragment-capped` 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:
- ```bash
- # 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**:
- 1. First search with `--robot-format sessions` outputs one session path per line
- 2. Second search with `--sessions-from <file>` restricts search to those sessions
- 3. 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 `--highlight` 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:
- ```bash
- 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:
- ```bash
- # 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 `--until` 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 `--limit` 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 `--limit 10` 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` |
- `--robot-meta` says which kind of number you got:
- ```bash
- 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 (`--limit 10`, 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.** `--aggregate` 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:
- ```bash
- 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):
- ```bash
- 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:
- ```bash
- 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:
- ```bash
- 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 |
- |------|---------|
- | `--robot` / `--json` | JSON output (pretty-printed) |
- | `--robot-format jsonl\|compact` | Streaming or single-line JSON |
- | `--robot-meta` | 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) |
- | `--fields minimal\|summary\|<list>` | Reduce payload size |
- | `--max-content-length N` | Truncate content fields to N chars |
- | `--max-tokens N` | Apply an approximate token budget to robot output |
- | `--timeout N` | Timeout in milliseconds. On expiry `search`/`pack` still exit 0 and emit `{"hits": [], "budget": {"timed_out": true, "skipped_sections": [...], "recommended_next_probe": "<command>", ...}}`; `--robot-format sessions` fails with exit 10, kind `timeout` |
- | `--cursor <token>` | Cursor-based pagination (from `_meta.next_cursor`) |
- | `--request-id ID` | Echoed in response for correlation |
- | `--aggregate agent,workspace,date` | Server-side aggregations |
- | `--explain` | Include query analysis (parsed query, cost estimate) |
- | `--dry-run` | Validate query without executing |
- | `--no-maintenance` | 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 `--refresh` and `--daemon`) |
- | `--source <source>` | Filter by source: `local`, `remote`, `all`, or specific source ID |
- | `--highlight` | Also mark query-term occurrences the engine left unmarked (snippets always mark matched terms with `**`) |
- ### Index Flags Reference
- | Flag | Purpose |
- |------|---------|
- | `--idempotency-key KEY` | Safe retries: same key + params returns cached result (24h TTL) |
- | `--json` | JSON output with stats |
- | `--gc` | 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 --json` reports the reclaimable bytes under `storage_pressure.full_rebuild_readiness` (GH #453) |
- | `--rebuild-profile bounded` | 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. `--json` 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 --json` or `status --json` 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 --full` also rescans the session sources. A missing count provides
- no hollow-generation verdict.
- `index.manifest_source` (also under search `--robot-meta`
- `_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 --full --rebuild-profile bounded --json` 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 `--force-rebuild` still requests a fresh pass: it never
- reuses a generation from before it started. If that pass is itself
- interrupted, rerunning `cass index --force-rebuild` 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 `--full` 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](docs/perf/issue-496-lexical-resume.md) for the test matrix and measured
- scope.
- ### Robot Documentation System
- For machine-readable documentation, use `cass robot-docs <topic>`:
- | 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-codes` | Exit code meanings and retry guidance |
- | `examples` | Copy-paste usage examples |
- | `contracts` | API contract version and stability |
- | `sources` | Remote sources configuration guide |
- ```bash
- # 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:
- ```bash
- 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 `--robot` output
- - Flag names and behaviors
- - `_meta` block 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.
- ```
- ---
- ## 🔤 Query Language Reference
- `cass` supports a rich query syntax designed for both humans and machines.
- ### Basic Queries
- | Query | Matches |
- |-------|---------|
- | `error` | Messages containing "error" (case-insensitive) |
- | `python error` | Messages containing both "python" AND "error" |
- | `"authentication failed"` | Exact phrase match |
- | `auth fail` | Both terms, in any order |
- ### Boolean Operators
- Combine terms with explicit operators for complex queries:
- | Operator | Example | Meaning |
- |----------|---------|---------|
- | `AND` | `python AND error` | Both terms required (default) |
- | `OR` | `error OR warning` | Either term matches |
- | `NOT` | `error NOT test` | First term, excluding second |
- | `-` | `error -test` | Shorthand for NOT |
- **Operator Precedence**: NOT binds tightest, then AND (explicit, `&&`, or implied between words), then OR (`OR`, `||`). Parentheses group, in the TUI and robot mode alike: `a OR b c` means `a OR (b AND c)`, while `(a OR b) c` needs the parentheses. A `(` groups only at the start of a word, so code such as `foo(bar)` stays one term. `NOT NOT x` is `x`. Unbalanced parentheses are recovered rather than rejected. The SQLite fallback lanes, used while no lexical index is available, apply the same grammar.
- **Titles count as message text.** Each message is matched together with its conversation's title, which is often the conversation's first prompt. A term that appears only in the title therefore matches every message of that conversation, and `x NOT y` drops every message of a conversation whose title contains `y`. For example, in a conversation titled `fix auth tests`, `error NOT tests` returns none of its messages.
- ```bash
- # Complex boolean query
- cass search "authentication AND (error OR failure) NOT test" --robot
- # Exclude test files
- cass search "bug fix -test -spec" --robot
- # Either error type
- cass search "TypeError OR ValueError" --robot
- ```
- ### Phrase Queries
- Wrap terms in double quotes for exact phrase matching:
- | Query | Matches |
- |-------|---------|
- | `"file not found"` | Exact sequence "file not found" |
- | `"cannot read property"` | Exact JavaScript error message |
- | `"def test_"` | Function definitions starting with test_ |
- Phrases match their words adjacent and in order (no slop). Useful for error messages, code patterns, and specific terminology.
- ### Wildcard Patterns
- | Pattern | Type | Matches | Performance |
- |---------|------|---------|-------------|
- | `auth*` | Prefix | "auth", "authentication", "authorize" | Fast (uses edge n-grams) |
- | `*tion` | Suffix | "authentication", "function", "exception" | Slower (term-dictionary expansion) |
- | `*config*` | Substring | "reconfigure", "config.json", "misconfigured" | Slowest (term-dictionary expansion) |
- | `test_*` | Prefix on `test` | anything whose token starts with "test" | Fast |
- **Tip**: Ordinary ASCII prefix wildcards (`foo*`) retain the existing edge n-grams: prefixes of 2–20 characters, taken from titles and from the first 4 KiB of each message. Suffix and substring wildcards expand over the index's term dictionary, at most 16,384 terms per pattern; a pattern matching more terms fails rather than scanning. ASCII punctuation separates terms: `test_*` is a prefix match on `test`, `c++` searches for `c`, and `foo.bar` means `foo` AND `bar` anywhere in the message. Phrases (`"..."`) match adjacent words in order (slop 0).
- Accented Latin queries use the same fragments as the existing index. For example,
- `"kérlek"` requires adjacent exact `k` and `rlek` terms in one field. Bare words
- of 2–20 Unicode scalars retain the existing implicit final-token prefix:
- `kérlek` also matches `kérleknek`, while `"kérlek"` does not. An explicit
- `kérl*` requires `k` followed by a term starting with `rl`. These prefixes search the full
- dictionary, including text beyond the first 4 KiB and prefixes longer than 20
- characters. They allow up to 1,024 matching terms per field and immutable index
- segment; exceeding that budget returns an error instead of a partial result.
- If a final accented character was discarded by the original tokenizer, the last
- surviving fragment stays exact: `café*` searches for `caf`, not `cafeteria`.
- This correction reads the existing `v9-quill` index without a schema rebuild.
- The existing ingestion fingerprint policy may revalidate source files on the
- next incremental indexing run after the dependency update.
- It preserves the old tokenizer's limits: adjacent literal `k rlek` can match
- `kérlek`, and canonically equivalent Unicode spellings can produce different
- terms. Mixed CJK queries require the analyzer's actual terms in one field, with
- the existing conjunction behavior for overlapping bigrams. Unsupported scripts
- or an operand with no indexed terms refuse the whole nonempty query, including
- under `OR` and `NOT`; they cannot turn into an empty browse query. Accented
- suffix, substring and interior wildcard patterns are unsupported. A quoted
- phrase ignores edge stars under the existing syntax but rejects interior stars.
- ### Query Modifiers
- ```bash
- # Field-specific search (in robot mode)
- cass search "error" --agent claude --workspace /path/to/project
- # Time-bounded search
- cass search "bug" --since 2024-01-01 --until 2024-01-31
- cass search "bug" --today
- cass search "bug" --days 7
- # Combined filters
- cass search "authentication" --agent codex --workspace myproject --week
- ```
- ### Flexible Time Input
- `cass` accepts a wide variety of time/date formats for filtering:
- | Format | Examples | Description |
- |--------|----------|-------------|
- | **Relative** | `-7d`, `-24h`, `-30m`, `-1w` | Days, hours, minutes, weeks ago |
- | **Keywords** | `now`, `today`, `yesterday` | Named reference points |
- | **ISO 8601** | `2024-11-25`, `2024-11-25T14:30:00Z` | Standard datetime |
- | **US Dates** | `11/25/2024`, `11-25-2024` | Month/Day/Year |
- | **Unix Timestamp** | `1732579200`, `-1` | Seconds since epoch (negative before 1970) |
- | **Unix Millis** | `1732579200000`, `-315619200000` | Milliseconds (auto-detected) |
- **Intelligent Heuristics**:
- - Numbers whose absolute value is 100,000,000,000 (10^11) or more are milliseconds; smaller magnitudes are seconds
- - Years are written in full (`2024`, not `24`)
- - A value that names a whole day (a date without a time, `today`, `yesterday`) starts at local midnight as `--since` and runs through the day's last millisecond as `--until`, so `--until 2024-01-31` includes January 31
- - For `search` and `pack`, a `--since`/`--until` value that cannot be parsed, or a `--since` later than `--until`, is a usage error (exit 2, kind `usage`); it is never silently ignored
- ```bash
- # All equivalent for "last week"
- cass search "bug" --since -7d
- cass search "bug" --since "-1w"
- cass search "bug" --days 7
- # Date range
- cass search "feature" --since 2024-01-01 --until 2024-01-31
- # Mix formats
- cass search "error" --since yesterday --until now
- ```
- ### Match Types
- Search results include a `match_type` indicator. It describes the query, not each hit: every hit of a search carries the type of the least precise pattern in the query (e.g. `auth* *tion` stamps `suffix` on all hits).
- | Type | Meaning | Match Quality order |
- |------|---------|---------------------|
- | `exact` | No wildcards: exact terms (and edge n-gram prefixes) | 1 |
- | `prefix` | Trailing wildcard (`auth*`) | 2 |
- | `suffix` | Leading wildcard (`*tion`) | 3 |
- | `substring` | Both sides (`*config*`) | 4 |
- | `wildcard` | Inner wildcard (`f*o`) | 5 |
- | `implicit_wildcard` | Automatic wildcard fallback on a sparse exact search | 6 |
- Relevance scores carry no boost for the match type; only the TUI's Match Quality ranking mode (`F12`) orders by it.
- ### Auto-Fuzzy Fallback
- When an exact query's first page returns fewer than 3 results (or fewer than a smaller `--limit`), `cass` retries with wildcard expansion:
- - `auth` → `*auth*`
- - It runs only on indexes with at most 10,000 documents (`CASS_AUTOMATIC_WILDCARD_FALLBACK_MAX_DOCS`; `0` disables it), so on a typical real archive it does not run.
- - It skips queries that already use wildcards, boolean operators or phrases, and zero-hit queries containing a token longer than 16 characters.
- - The wildcard results replace the exact ones only when they find more hits; robot mode then reports `_meta.wildcard_fallback: true`. When a sparse result did not get the retry, `_meta.wildcard_fallback_skipped` says why: `index_over_automatic_limit` (the index is over the document cap), `automatic_retry_disabled` (the cap is `0`) or `long_query_term`; add explicit wildcards to run it anyway. When the retry itself runs out of query fuel, the exact results are returned and the field is `query_fuel_exhausted`
- - TUI shows a "fuzzy" indicator in the status bar
- ---
- ## ⌨️ Complete Keyboard Reference
- ### Global Keys
- | Key | Action |
- |-----|--------|
- | `Ctrl+C` | Force quit |
- | `Esc` / `F10` | Unwind: close the open modal or surface, otherwise quit |
- | `F1` / `Alt+?` | Toggle help screen |
- | `F2` / `Alt+T` | Next theme (cycles all 19 presets) |
- | `Shift+F2` / `Alt+Shift+T` | Previous theme |
- | `Ctrl+B` | Toggle border style (rounded/square) |
Lines 2,001–3,308 are not shown. The link to the file on GitHub has every line.
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.