Skip to content
Back to search

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/dicklesworthstone-coding-agent-session-search/badge.svg)](/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

i

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.

  1. ---
  2. name: cass
  3. 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."
  4. ---
  5. # CASS - Coding Agent Session Search
  6. 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.
  7. ## CRITICAL: Robot Mode Required for AI Agents
  8. **NEVER run bare `cass`** - it launches an interactive TUI that blocks your session!
  9. ```bash
  10. # WRONG - blocks terminal
  11. cass
  12. # CORRECT - JSON output for agents
  13. cass search "query" --robot
  14. cass search "query" --json # alias
  15. ```
  16. **Always use `--robot` or `--json` flags for machine-readable output.**
  17. ---
  18. ## Quick Reference for AI Agents
  19. ### Bounded History Retrieval
  20. For a quick project-history question, start with one scoped query. The flag set
  21. below is verified on cass 0.8.0; check `cass --version` and `cass search --help`
  22. once per installed version. If `--no-maintenance` is unsupported, stop and report
  23. the version mismatch; silently removing it permits maintenance.
  24. ```bash
  25. # Specific terms, one workspace, recent history, small cited result set
  26. cass search "performance regression" --workspace /path/to/project --days 7 \
  27. --mode lexical --no-maintenance --robot --robot-meta --fields minimal \
  28. --limit 5 --max-tokens 2000 --timeout 2000
  29. # Expand only a useful hit, using its exact source_path and line_number
  30. cass view /path/to/session.jsonl -n 42 -C 3 --json --timeout 2000
  31. ```
  32. `--timeout` is in milliseconds; `--max-tokens` is an approximate output budget,
  33. not a CPU or memory limit. Apply a caller-side wall-clock deadline as well (for
  34. example, GNU `timeout 10s` before the command). Exit 124 from that wrapper is an
  35. incomplete attempt; its interrupted stdout may not be valid JSON. In JSON search
  36. output, inspect `budget.timed_out` even after exit 0: empty timed-out hits do not
  37. prove that no history exists.
  38. `view -C 3` limits surrounding lines, not bytes or tokens; a single JSONL record
  39. can be large. Check its output size before adding excerpts to a prompt.
  40. Hybrid remains the product default. Explicit lexical mode keeps this workflow
  41. out of semantic inference; `--no-maintenance` prevents index repair, catch-up,
  42. and daemon auto-spawn. If it returns `maintenance-required`, report that blocker
  43. and stop this retrieval attempt. Do not turn a summary request into an index,
  44. repair, model-install, wildcard-aggregate, or repeated health/status workflow.
  45. Use readiness commands when diagnosing readiness; review their proposed actions
  46. before starting a separate mutating task. Broaden dates or terms deliberately
  47. after a completed query; choose semantic/hybrid only when conceptual retrieval
  48. is needed and its cost is acceptable. Preserve source/line citations in summaries.
  49. ### Essential Commands
  50. ```bash
  51. # Find the current session for this workspace
  52. cass sessions --current --json
  53. # List recent sessions for a specific project
  54. cass sessions --workspace "$(pwd)" --json --limit 5
  55. # Common agent flow: find current session, then export it
  56. cass export-html "$(cass sessions --current --json | jq -r '.sessions[0].path')" --json
  57. # Search with JSON output
  58. cass search "authentication error" --robot --limit 5
  59. # Search with metadata (elapsed_ms, cache stats, freshness)
  60. cass search "error" --robot --robot-meta
  61. # Minimal payload (path, line, agent only)
  62. cass search "bug" --robot --fields minimal
  63. # View source at specific line
  64. cass view /path/to/session.jsonl -n 42 --json
  65. # Expand context around a line
  66. cass expand /path/to/session.jsonl -n 42 -C 5 --json
  67. # Capabilities discovery
  68. cass capabilities --json
  69. # Full API schema
  70. cass introspect --json
  71. # LLM-optimized documentation
  72. cass robot-docs guide
  73. cass robot-docs commands
  74. cass robot-docs schemas
  75. cass robot-docs examples
  76. cass robot-docs exit-codes
  77. ```
  78. ---
  79. ## Why Use CASS
  80. ### Cross-Agent Knowledge Transfer
  81. Your coding agents create scattered knowledge:
  82. - Claude Code sessions in `~/.claude/projects`
  83. - Codex sessions in `~/.codex/sessions`
  84. - Cursor state in SQLite databases
  85. - Aider history in markdown files
  86. 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.
  87. ### Use Cases
  88. ```bash
  89. # "I solved this before..."
  90. cass search "TypeError: Cannot read property" --robot --days 30
  91. # Cross-agent learning (what has ANY agent said about X?)
  92. cass search "authentication" --robot --workspace /path/to/project
  93. # Agent-to-agent handoff
  94. cass search "database migration" --robot --fields summary
  95. # Daily review
  96. cass timeline --today --json
  97. ```
  98. ---
  99. ## Command Reference
  100. ### Indexing
  101. ```bash
  102. # Full rebuild of DB and search index
  103. cass index --full
  104. # Incremental update (since last scan)
  105. cass index
  106. # Watch mode: auto-reindex on file changes
  107. cass index --watch
  108. # Force rebuild even if schema unchanged
  109. cass index --full --force-rebuild
  110. # Safe retries with idempotency key (24h TTL)
  111. cass index --full --idempotency-key "build-$(date +%Y%m%d)"
  112. # JSON output with stats
  113. cass index --full --json
  114. ```
  115. ### Search
  116. ```bash
  117. # Basic search (JSON output required for agents!)
  118. cass search "query" --robot
  119. # With filters
  120. cass search "error" --robot --agent claude --days 7
  121. cass search "bug" --robot --workspace /path/to/project
  122. cass search "panic" --robot --today
  123. # Time filters
  124. cass search "auth" --robot --since 2024-01-01 --until 2024-01-31
  125. cass search "test" --robot --yesterday
  126. cass search "fix" --robot --week
  127. # Wildcards
  128. cass search "auth*" --robot # prefix: authentication, authorize
  129. cass search "*tion" --robot # suffix: authentication, exception
  130. cass search "*config*" --robot # substring: misconfigured
  131. # Token budget management (critical for LLMs!)
  132. cass search "error" --robot --fields minimal # path, line, agent only
  133. cass search "error" --robot --fields summary # adds title, score
  134. cass search "error" --robot --max-content-length 500 # truncate fields
  135. cass search "error" --robot --max-tokens 2000 # soft budget (~4 chars/token)
  136. cass search "error" --robot --limit 5 # cap results
  137. # Pagination (cursor-based)
  138. cass search "TODO" --robot --robot-meta --limit 20
  139. # Use _meta.next_cursor from response:
  140. cass search "TODO" --robot --robot-meta --limit 20 --cursor "eyJ..."
  141. # Match highlighting
  142. cass search "authentication error" --robot --highlight
  143. # Query analysis/debugging
  144. cass search "auth*" --robot --explain # parsed query, cost estimates
  145. cass search "auth error" --robot --dry-run # validate without executing
  146. # Aggregations (server-side counts)
  147. cass search "error" --robot --aggregate agent,workspace,date
  148. # Request correlation
  149. cass search "bug" --robot --request-id "req-12345"
  150. # Source filtering (for multi-machine setups)
  151. cass search "auth" --robot --source laptop
  152. cass search "error" --robot --source remote
  153. # Traceability (for debugging agent pipelines)
  154. cass search "error" --robot --trace-file /tmp/cass-trace.json
  155. ```
  156. ### Session Analysis
  157. ```bash
  158. # Export conversation to markdown/HTML/JSON
  159. cass export /path/to/session.jsonl --format markdown -o conversation.md
  160. cass export /path/to/session.jsonl --format html -o conversation.html
  161. cass export /path/to/session.jsonl --format json --include-tools
  162. # Expand context around a line (from search result)
  163. cass expand /path/to/session.jsonl -n 42 -C 5 --json
  164. # Shows 5 messages before and after line 42
  165. # View source at line
  166. cass view /path/to/session.jsonl -n 42 --json
  167. # Activity timeline
  168. cass timeline --today --json --group-by hour
  169. cass timeline --days 7 --json --agent claude
  170. cass timeline --since 7d --json
  171. # Find related sessions for a file
  172. cass context /path/to/source.ts --json
  173. ```
  174. ### Status & Diagnostics
  175. ```bash
  176. # Readiness diagnosis, when needed; not a prerequisite for every query
  177. cass health --json
  178. # Full status snapshot
  179. cass status --json
  180. cass state --json # alias
  181. # Statistics
  182. cass stats --json
  183. cass stats --by-source # for multi-machine
  184. # Full diagnostics
  185. cass diag --verbose
  186. ```
  187. ---
  188. ## Aggregation & Analytics
  189. Aggregate search results server-side to get counts and distributions without transferring full result data:
  190. Aggregations reduce output volume, not necessarily scan work. They are not the
  191. first step for a quick history question; use the scoped retrieval recipe above.
  192. ```bash
  193. # Count results by agent
  194. cass search "error" --robot --aggregate agent
  195. # → { "aggregations": { "agent": { "buckets": [{"key": "claude_code", "count": 45}, ...] } } }
  196. # Multi-field aggregation
  197. cass search "bug" --robot --aggregate agent,workspace,date
  198. # Combine with filters
  199. cass search "TODO" --agent claude --robot --aggregate workspace
  200. ```
  201. | Aggregation Field | Description |
  202. |-------------------|-------------|
  203. | `agent` | Group by agent type (claude_code, codex, cursor, etc.) |
  204. | `workspace` | Group by workspace/project path |
  205. | `date` | Group by date (YYYY-MM-DD) |
  206. | `match_type` | Group by match quality (exact, prefix, fuzzy) |
  207. Top 10 buckets returned per field, with `other_count` for remaining items.
  208. ---
  209. ## Remote Sources (Multi-Machine Search)
  210. Search across sessions from multiple machines via SSH/rsync.
  211. ### Setup Wizard (Recommended)
  212. ```bash
  213. cass sources setup
  214. ```
  215. The wizard:
  216. 1. Discovers SSH hosts from `~/.ssh/config`
  217. 2. Probes each for agent data and cass installation
  218. 3. Optionally installs cass on remotes
  219. 4. Indexes sessions on remotes
  220. 5. Configures `sources.toml`
  221. 6. Syncs data locally
  222. ```bash
  223. cass sources setup --hosts css,csd,yto # Specific hosts only
  224. cass sources setup --dry-run # Preview without changes
  225. cass sources setup --resume # Resume interrupted setup
  226. ```
  227. ### Manual Setup
  228. ```bash
  229. # Add a remote machine
  230. cass sources add user@laptop.local --preset macos-defaults
  231. cass sources add dev@workstation --path ~/.claude/projects --path ~/.codex/sessions
  232. # List sources
  233. cass sources list --json
  234. # Sync sessions
  235. cass sources sync
  236. cass sources sync --source laptop --verbose
  237. # Check connectivity
  238. cass sources doctor
  239. cass sources doctor --source laptop --json
  240. # Path mappings (rewrite remote paths to local)
  241. cass sources mappings list laptop
  242. cass sources mappings add laptop --from /home/user/projects --to /Users/me/projects
  243. cass sources mappings test laptop /home/user/projects/myapp/src/main.rs
  244. # Remove source
  245. cass sources remove laptop --purge -y
  246. ```
  247. Configuration stored in `~/.config/cass/sources.toml` (Linux) or `~/Library/Application Support/cass/sources.toml` (macOS).
  248. ---
  249. ## Robot Mode Deep Dive
  250. ### Self-Documenting API
  251. CASS teaches agents how to use itself:
  252. ```bash
  253. # Quick capability check
  254. cass capabilities --json
  255. # Returns: features, connectors, limits
  256. # Full API schema
  257. cass introspect --json
  258. # Returns: all commands, arguments, response shapes
  259. # Topic-based docs (LLM-optimized)
  260. cass robot-docs commands # all commands and flags
  261. cass robot-docs schemas # response JSON schemas
  262. cass robot-docs examples # copy-paste invocations
  263. cass robot-docs exit-codes # error handling
  264. cass robot-docs guide # quick-start walkthrough
  265. cass robot-docs contracts # API versioning
  266. cass robot-docs sources # remote sources guide
  267. ```
  268. ### Forgiving Syntax (Agent-Friendly)
  269. CASS auto-corrects common mistakes:
  270. | What you type | What CASS understands |
  271. |---------------|----------------------|
  272. | `cass serach "error"` | `cass search "error"` (typo corrected) |
  273. | `cass -robot -limit=5` | `cass --robot --limit=5` (single-dash fixed) |
  274. | `cass --Robot --LIMIT 5` | `cass --robot --limit 5` (case normalized) |
  275. | `cass find "auth"` | `cass search "auth"` (alias resolved) |
  276. | `cass --limt 5` | `cass --limit 5` (Levenshtein <=2) |
  277. **Command Aliases:**
  278. - `find`, `query`, `q`, `lookup`, `grep` → `search`
  279. - `ls`, `list`, `info`, `summary` → `stats`
  280. - `st`, `state` → `status`
  281. - `reindex`, `idx`, `rebuild` → `index`
  282. - `show`, `get`, `read` → `view`
  283. - `docs`, `help-robot`, `robotdocs` → `robot-docs`
  284. ### Output Formats
  285. ```bash
  286. # Pretty-printed JSON (default)
  287. cass search "error" --robot
  288. # Streaming JSONL (header + one hit per line)
  289. cass search "error" --robot-format jsonl
  290. # Compact single-line JSON
  291. cass search "error" --robot-format compact
  292. # With performance metadata
  293. cass search "error" --robot --robot-meta
  294. ```
  295. **Design principle:** stdout = JSON only; diagnostics go to stderr.
  296. ### Token Budget Management
  297. LLMs have context limits. Control output size:
  298. | Flag | Effect |
  299. |------|--------|
  300. | `--fields minimal` | Only `source_path`, `line_number`, `agent` |
  301. | `--fields summary` | Adds `title`, `score` |
  302. | `--fields score,title,snippet` | Custom field selection |
  303. | `--max-content-length 500` | Truncate long fields (UTF-8 safe) |
  304. | `--max-tokens 2000` | Soft budget (~4 chars/token) |
  305. | `--limit 5` | Cap number of results |
  306. Truncated fields include `*_truncated: true` indicator.
  307. ---
  308. ## Structured Error Handling
  309. Errors are JSON with actionable hints:
  310. ```json
  311. {
  312. "error": {
  313. "code": 3,
  314. "kind": "index_missing",
  315. "message": "Search index not found",
  316. "hint": "Run 'cass index --full' to build the index",
  317. "retryable": false
  318. }
  319. }
  320. ```
  321. ### Exit Codes
  322. | Code | Meaning | Action |
  323. |------|---------|--------|
  324. | 0 | Success | Parse stdout |
  325. | 1 | Health check failed | Inspect the reported condition; no automatic rebuild |
  326. | 2 | Usage error | Fix syntax (hint provided) |
  327. | 3 | Index/DB missing | Report missing assets; indexing is a separate mutating task |
  328. | 4 | Network error | Check connectivity |
  329. | 5 | Data/maintenance failure | Read error kind; preserve the archive and report the blocker |
  330. | 6 | Incompatible version | Update cass |
  331. | 7 | Lock/busy | Retry later |
  332. | 8 | Partial result | Report incomplete coverage; do not silently retry |
  333. | 9 | Unknown error | Check `retryable` flag |
  334. Codes are command-specific: consult `cass robot-docs exit-codes` and the JSON
  335. error kind. Search budget expiry can return exit 0 with `budget.timed_out=true`;
  336. session-path output instead uses exit 10 for timeout.
  337. ---
  338. ## Search Modes
  339. Three search modes, selectable with `--mode` flag:
  340. | Mode | Algorithm | Best For |
  341. |------|-----------|----------|
  342. | **lexical** | BM25 full-text | Exact term matching, bounded history recipes |
  343. | **semantic** | Vector similarity | Conceptual queries, "find similar" |
  344. | **hybrid** (default) | Reciprocal Rank Fusion | Lexical retrieval with semantic refinement when ready |
  345. ```bash
  346. cass search "authentication" --mode lexical --robot
  347. cass search "how to handle user login" --mode semantic --robot
  348. cass search "auth error handling" --mode hybrid --robot
  349. ```
  350. **Hybrid** combines lexical and semantic using RRF:
  351. ```
  352. RRF_score = Σ 1 / (60 + rank_i)
  353. ```
  354. ---
  355. ## Pipeline Mode (Chained Search)
  356. Chain searches by piping session paths:
  357. ```bash
  358. # Find sessions mentioning "auth", then search within those for "token"
  359. cass search "authentication" --robot-format sessions | \
  360. cass search "refresh token" --sessions-from - --robot
  361. # Build a filtered corpus from today's work
  362. cass search --today --robot-format sessions > today_sessions.txt
  363. cass search "bug fix" --sessions-from today_sessions.txt --robot
  364. ```
  365. Use cases:
  366. - **Drill-down**: Broad search → narrow within results
  367. - **Cross-reference**: Find sessions with term A, then find term B within them
  368. - **Corpus building**: Save session lists for repeated searches
  369. ---
  370. ## Query Language
  371. ### Basic Queries
  372. | Query | Matches |
  373. |-------|---------|
  374. | `error` | Messages containing "error" (case-insensitive) |
  375. | `python error` | Both "python" AND "error" |
  376. | `"authentication failed"` | Exact phrase |
  377. ### Boolean Operators
  378. | Operator | Example | Meaning |
  379. |----------|---------|---------|
  380. | `AND` | `python AND error` | Both terms required (default) |
  381. | `OR` | `error OR warning` | Either term matches |
  382. | `NOT` | `error NOT test` | First term, excluding second |
  383. | `-` | `error -test` | Shorthand for NOT |
  384. ```bash
  385. # Complex boolean query
  386. cass search "authentication AND (error OR failure) NOT test" --robot
  387. # Exclude test files
  388. cass search "bug fix -test -spec" --robot
  389. # Either error type
  390. cass search "TypeError OR ValueError" --robot
  391. ```
  392. ### Wildcard Patterns
  393. | Pattern | Type | Performance |
  394. |---------|------|-------------|
  395. | `auth*` | Prefix | Fast (edge n-grams) |
  396. | `*tion` | Suffix | Slower (regex) |
  397. | `*config*` | Substring | Slowest (regex) |
  398. ### Match Types
  399. Results include `match_type`:
  400. | Type | Meaning | Score Boost |
  401. |------|---------|-------------|
  402. | `exact` | Verbatim match | Highest |
  403. | `prefix` | Via prefix expansion | High |
  404. | `suffix` | Via suffix pattern | Medium |
  405. | `substring` | Via substring pattern | Lower |
  406. | `fuzzy` | Auto-fallback (sparse results) | Lowest |
  407. ### Auto-Fuzzy Fallback
  408. When exact query returns <3 results, CASS automatically retries with wildcards:
  409. - `auth` → `*auth*`
  410. - Results flagged with `wildcard_fallback: true`
  411. ### Flexible Time Input
  412. CASS accepts a wide variety of time/date formats:
  413. | Format | Examples |
  414. |--------|----------|
  415. | **Relative** | `-7d`, `-24h`, `-30m`, `-1w` |
  416. | **Keywords** | `now`, `today`, `yesterday` |
  417. | **ISO 8601** | `2024-11-25`, `2024-11-25T14:30:00Z` |
  418. | **US Dates** | `11/25/2024`, `11-25-2024` |
  419. | **Unix Timestamp** | `1732579200` (seconds or milliseconds) |
  420. ---
  421. ## Ranking Modes
  422. Cycle with `F12` in TUI or use `--ranking` flag:
  423. | Mode | Formula | Best For |
  424. |------|---------|----------|
  425. | **Recent Heavy** | `relevance*0.3 + recency*0.7` | "What was I working on?" |
  426. | **Balanced** | `relevance*0.5 + recency*0.5` | General search |
  427. | **Relevance** | `relevance*0.8 + recency*0.2` | "Best explanation of X" |
  428. | **Match Quality** | Penalizes fuzzy matches | Precise technical searches |
  429. | **Date Newest** | Pure chronological | Recent activity |
  430. | **Date Oldest** | Reverse chronological | "When did I first..." |
  431. ### Score Components
  432. - **Text Relevance (BM25)**: Term frequency, inverse document frequency, length normalization
  433. - **Recency**: Exponential decay (today ~1.0, last week ~0.7, last month ~0.3)
  434. - **Match Exactness**: Exact phrase=1.0, Prefix=0.9, Suffix=0.8, Substring=0.6, Fuzzy=0.4
  435. ### Blended Scoring Formula
  436. ```
  437. Final_Score = BM25_Score × Match_Quality + α × Recency_Factor
  438. ```
  439. | Mode | α Value | Effect |
  440. |------|---------|--------|
  441. | Recent Heavy | 1.0 | Recency dominates |
  442. | Balanced | 0.4 | Moderate recency boost |
  443. | Relevance Heavy | 0.1 | BM25 dominates |
  444. | Match Quality | 0.0 | Pure text matching |
  445. ---
  446. ## Supported Agents (23 Connectors)
  447. | Agent | Location | Format |
  448. |-------|----------|--------|
  449. | **Claude Code** | `~/.claude/projects` | JSONL |
  450. | **Codex** | `~/.codex/sessions` | JSONL (Rollout) |
  451. | **Gemini CLI** | `~/.gemini/tmp` | JSON |
  452. | **Cline** | VS Code global storage | Task directories |
  453. | **OpenCode** | `.opencode` directories | SQLite |
  454. | **Amp** | `~/.local/share/amp` + VS Code | Mixed |
  455. | **Cursor** | `~/Library/Application Support/Cursor` | SQLite (state.vscdb) |
  456. | **ChatGPT** | `~/Library/Application Support/com.openai.chat` | JSON (v1 unencrypted) |
  457. | **Aider** | `~/.aider.chat.history.md` + per-project | Markdown |
  458. | **Pi-Agent** | `~/.pi/agent/sessions` | JSONL with thinking |
  459. | **Factory (Droid)** | `~/.factory/sessions` | JSONL by workspace |
  460. | **GitHub Copilot Chat** | VS Code global storage | JSON / SQLite |
  461. | **GitHub Copilot CLI** | `~/.copilot/session-state` | JSONL |
  462. | **OpenClaw** | `~/.openclaw` | JSONL |
  463. | **ClawdBot** | `~/.clawdbot` | JSONL |
  464. | **Vibe** | `~/.vibe/logs/session` | JSONL |
  465. | **Crush** | `~/.crush/crush.db` | SQLite |
  466. | **Hermes** | `~/.hermes` | JSONL |
  467. | **Kimi Code** | `~/.kimi/sessions` | JSONL |
  468. | **Qwen Code** | `~/.qwen/tmp` | JSON / JSONL |
  469. | **OpenHands** | `~/.openhands/conversations` | JSON event stream |
  470. | **Antigravity** | `~/.gemini/antigravity-cli` | JSONL / SQLite |
  471. | **Grok Build** | `$GROK_HOME/sessions` (default `~/.grok/sessions`) | ACP updates JSONL |
  472. **Note:** ChatGPT v2/v3 are AES-256-GCM encrypted (keychain access required). Legacy v1 unencrypted conversations are indexed automatically.
  473. ---
  474. ## TUI Features (for Humans)
  475. Launch with `cass` (no flags):
  476. ### Keyboard Shortcuts
  477. **Navigation:**
  478. - `Up/Down`: Move selection
  479. - `Left/Right`: Switch panes
  480. - `Tab/Shift+Tab`: Cycle focus
  481. - `Enter`: Open in `$EDITOR`
  482. - `Space`: Full-screen detail view
  483. - `Home/End`: Jump to first/last result
  484. - `PageUp/PageDown`: Scroll by page
  485. **Filtering:**
  486. - `F3`: Agent filter
  487. - `F4`: Workspace filter
  488. - `F5/F6`: Time filters (from/to)
  489. - `Shift+F3`: Scope to current result's agent
  490. - `Shift+F4`: Clear workspace filter
  491. - `Shift+F5`: Cycle presets (24h/7d/30d/all)
  492. - `Ctrl+Del`: Clear all filters
  493. **Modes:**
  494. - `F2`: Toggle theme (6 presets)
  495. - `F7`: Context window size (S/M/L/XL)
  496. - `F9`: Match mode (prefix/standard)
  497. - `F12`: Ranking mode
  498. - `Ctrl+B`: Toggle border style
  499. **Selection & Actions:**
  500. - `m`: Toggle selection
  501. - `Ctrl+A`: Select all
  502. - `A`: Bulk actions menu
  503. - `Ctrl+Enter`: Add to queue
  504. - `Ctrl+O`: Open all queued
  505. - `y`: Copy path/content
  506. - `Ctrl+Y`: Copy all selected
  507. - `/`: Find in detail pane
  508. - `n/N`: Next/prev match
  509. **Views & Palette:**
  510. - `Ctrl+P`: Command palette
  511. - `1-9`: Load saved view
  512. - `Shift+1-9`: Save view to slot
  513. **Source Filtering (multi-machine):**
  514. - `F11`: Cycle source filter (all/local/remote)
  515. - `Shift+F11`: Source selection menu
  516. **Global:**
  517. - `Ctrl+C`: Quit
  518. - `F1` or `?`: Toggle help
  519. - `Ctrl+Shift+R`: Force re-index
  520. - `Ctrl+Shift+Del`: Reset all TUI state
  521. ### Detail Pane Tabs
  522. | Tab | Content | Switch With |
  523. |-----|---------|-------------|
  524. | **Messages** | Full conversation with markdown | `[` / `]` |
  525. | **Snippets** | Keyword-extracted summaries | `[` / `]` |
  526. | **Raw** | Unformatted JSON/text | `[` / `]` |
  527. ### Context Window Sizing
  528. | Size | Characters | Use Case |
  529. |------|------------|----------|
  530. | **Small** | ~200 | Quick scanning |
  531. | **Medium** | ~400 | Default balanced view |
  532. | **Large** | ~800 | Longer passages |
  533. | **XLarge** | ~1600 | Full context, code review |
  534. **Peek Mode** (`Ctrl+Space`): Temporarily expand to XL without changing default.
  535. ---
  536. ## Theme Presets
  537. Cycle through 6 built-in themes with `F2`:
  538. | Theme | Description | Best For |
  539. |-------|-------------|----------|
  540. | **Dark** | Tokyo Night-inspired deep blues | Low-light environments |
  541. | **Light** | High-contrast light background | Bright environments |
  542. | **Catppuccin** | Warm pastels, reduced eye strain | All-day coding |
  543. | **Dracula** | Purple-accented dark theme | Popular developer theme |
  544. | **Nord** | Arctic-inspired cool tones | Calm, focused work |
  545. | **High Contrast** | Maximum readability | Accessibility needs |
  546. All themes validated against WCAG contrast requirements (4.5:1 minimum for text).
  547. ### Role-Aware Message Styling
  548. | Role | Visual Treatment |
  549. |------|------------------|
  550. | **User** | Blue-tinted background, bold |
  551. | **Assistant** | Green-tinted background |
  552. | **System** | Gray/muted background |
  553. | **Tool** | Orange-tinted background |
  554. ---
  555. ## Saved Views
  556. Save filter configurations to 9 slots for instant recall.
  557. **What Gets Saved:**
  558. - Active filters (agent, workspace, time range)
  559. - Current ranking mode
  560. - The search query
  561. **Keyboard:**
  562. - `Shift+1` through `Shift+9`: Save current view
  563. - `1` through `9`: Load view from slot
  564. **Via Command Palette:** `Ctrl+P` → "Save/Load view"
  565. Views persist in `tui_state.json` across sessions.
  566. ---
  567. ## Density Modes
  568. Control lines per search result. Cycle with `Shift+D`:
  569. | Mode | Lines | Best For |
  570. |------|-------|----------|
  571. | **Compact** | 3 | Maximum results visible |
  572. | **Cozy** | 5 | Balanced view (default) |
  573. | **Spacious** | 8 | Detailed preview |
  574. ---
  575. ## Bookmark System
  576. Save important results with notes and tags:
  577. In TUI: Press `b` to bookmark, add notes and tags.
  578. **Bookmark Structure:**
  579. - `title`: Short description
  580. - `source_path`, `line_number`, `agent`, `workspace`
  581. - `note`: Your annotations
  582. - `tags`: Comma-separated labels
  583. - `snippet`: Extracted content
  584. Storage: `~/.local/share/coding-agent-search/bookmarks.db` (SQLite)
  585. ---
  586. ## Optional Semantic Search
  587. Local-only semantic search using MiniLM (no cloud):
  588. **Required files** (place in data directory):
  589. - `model.onnx`
  590. - `tokenizer.json`
  591. - `config.json`
  592. - `special_tokens_map.json`
  593. - `tokenizer_config.json`
  594. Vector index stored as `vector_index/index-minilm-384.cvvi`.
  595. CASS does NOT auto-download models; you must manually install them.
  596. **Hash Embedder Fallback:** When MiniLM not installed, CASS uses a hash-based embedder for approximate semantic similarity.
  597. ---
  598. ## Watch Mode
  599. Real-time index updates:
  600. ```bash
  601. cass index --watch
  602. ```
  603. - **Debounce:** 2 seconds (wait for burst to settle)
  604. - **Max wait:** 5 seconds (force flush during continuous activity)
  605. - **Incremental:** Only re-scans modified files
  606. TUI automatically starts watch mode in background.
  607. ---
  608. ## Deduplication Strategy
  609. CASS uses multi-layer deduplication:
  610. 1. **Message Hash**: SHA-256 of `(role + content + timestamp)` - identical messages stored once
  611. 2. **Conversation Fingerprint**: Hash of first N message hashes - detects duplicate files
  612. 3. **Search-Time Dedup**: Results deduplicated by content similarity
  613. **Noise Filtering:**
  614. - Empty messages and pure whitespace
  615. - System prompts (unless searching for them)
  616. - Repeated tool acknowledgments
  617. ---
  618. ## Performance Characteristics
  619. Latency and memory depend on archive size, index readiness, model state, and
  620. whether the process is cold. Historical small-corpus timings are not deadlines
  621. for a large archive. Measure the complete command, bound each retrieval attempt,
  622. and distinguish successful results from timeout or maintenance refusal.
  623. ---
  624. ## Response Shapes
  625. **Search Response:**
  626. ```json
  627. {
  628. "query": "error",
  629. "limit": 10,
  630. "count": 5,
  631. "total_matches": 42,
  632. "hits": [
  633. {
  634. "source_path": "/path/to/session.jsonl",
  635. "line_number": 123,
  636. "agent": "claude_code",
  637. "workspace": "/projects/myapp",
  638. "title": "Authentication debugging",
  639. "snippet": "The error occurs when...",
  640. "score": 0.85,
  641. "match_type": "exact",
  642. "created_at": "2024-01-15T10:30:00Z"
  643. }
  644. ],
  645. "_meta": {
  646. "elapsed_ms": 12,
  647. "cache_hit": true,
  648. "wildcard_fallback": false,
  649. "next_cursor": "eyJ...",
  650. "index_freshness": { "stale": false, "age_seconds": 120 }
  651. }
  652. }
  653. ```
  654. **Aggregation Response:**
  655. ```json
  656. {
  657. "aggregations": {
  658. "agent": {
  659. "buckets": [
  660. {"key": "claude_code", "count": 120},
  661. {"key": "codex", "count": 85}
  662. ],
  663. "other_count": 15
  664. }
  665. }
  666. }
  667. ```
  668. ---
  669. ## Environment Variables
  670. | Variable | Purpose |
  671. |----------|---------|
  672. | `CASS_DATA_DIR` | Override data directory |
  673. | `CHATGPT_ENCRYPTION_KEY` | Base64 key for encrypted ChatGPT |
  674. | `PI_CODING_AGENT_DIR` | Override Pi-Agent sessions path |
  675. | `CASS_CACHE_SHARD_CAP` | Per-shard cache entries (default 256) |
  676. | `CASS_CACHE_TOTAL_CAP` | Total cached hits (default 2048) |
  677. | `CASS_DEBUG_CACHE_METRICS` | Enable cache debug logging |
  678. | `CODING_AGENT_SEARCH_NO_UPDATE_PROMPT` | Skip update checks |
  679. ---
  680. ## Shell Completions
  681. ```bash
  682. cass completions bash > ~/.local/share/bash-completion/completions/cass
  683. cass completions zsh > "${fpath[1]}/_cass"
  684. cass completions fish > ~/.config/fish/completions/cass.fish
  685. cass completions powershell >> $PROFILE
  686. ```
  687. ---
  688. ## API Contract & Versioning
  689. ```bash
  690. cass api-version --json
  691. # → { "version": "0.4.0", "contract_version": "1", "breaking_changes": [] }
  692. cass introspect --json
  693. # → Full schema: all commands, arguments, response types
  694. ```
  695. **Guaranteed Stable:**
  696. - Exit codes and their meanings
  697. - JSON response structure for `--robot` output
  698. - Flag names and behaviors
  699. - `_meta` block format
  700. ---
  701. ## Integration with CASS Memory (cm)
  702. CASS provides **episodic memory** (raw sessions). CM extracts **procedural memory** (rules and playbooks):
  703. ```bash
  704. # 1. CASS indexes raw sessions
  705. cass index --full
  706. # 2. Search for relevant past experience
  707. cass search "authentication timeout" --robot --limit 10
  708. # 3. CM reflects on sessions to extract rules
  709. cm reflect
  710. ```
  711. ---
  712. ## Troubleshooting
  713. | Issue | Solution |
  714. |-------|----------|
  715. | "missing index" / `maintenance-required` | Report the blocker; separate retrieval from authorized indexing/repair |
  716. | Stale warning | Report the age/coverage; decide separately whether to refresh |
  717. | Empty results | Check `budget.timed_out`; then reconsider query scope if the attempt completed |
  718. | JSON parsing errors | Use `--robot-format compact` |
  719. | Watch not triggering | Check `watch_state.json`, verify file event support |
  720. | Reset TUI state | `cass tui --reset-state` or `Ctrl+Shift+Del` |
  721. ---
  722. ## Installation
  723. ```bash
  724. # One-liner install
  725. curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/coding_agent_session_search/main/install.sh \
  726. | bash -s -- --easy-mode --verify
  727. # Windows
  728. irm https://raw.githubusercontent.com/Dicklesworthstone/coding_agent_session_search/main/install.ps1 | iex
  729. ```
  730. ---
  731. ## Integration with Flywheel
  732. | Tool | Integration |
  733. |------|-------------|
  734. | **CM** | CASS provides episodic memory, CM extracts procedural memory |
  735. | **NTM** | Robot mode flags for searching past sessions |
  736. | **Agent Mail** | Search threads across agent history |
  737. | **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.

  1. # 🔎 coding-agent-search (cass)
  2. <div align="center">
  3. <img src="docs/assets/images/cass_illustration.webp" alt="coding-agent-search (cass) illustration">
  4. </div>
  5. ![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-blue.svg)
  6. ![Rust](https://img.shields.io/badge/Rust-pinned%20nightly-orange.svg)
  7. ![Status](https://img.shields.io/badge/status-alpha-purple.svg)
  8. ![License](https://img.shields.io/badge/license-MIT%2BOpenAI%2FAnthropic%20Rider-green.svg)
  9. **Unified, high-performance TUI to index and search your local coding agent history.**
  10. 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.
  11. <div align="center">
  12. ```bash
  13. curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/coding_agent_session_search/main/install.sh?$(date +%s)" \
  14. | bash -s -- --easy-mode --verify
  15. ```
  16. ```powershell
  17. # Windows (PowerShell)
  18. & ([scriptblock]::Create((irm "https://raw.githubusercontent.com/Dicklesworthstone/coding_agent_session_search/main/install.ps1"))) -EasyMode -Verify
  19. ```
  20. Installs the latest release by default. Pass `--version <tag>` / `-Version <tag>` to pin a specific version.
  21. **Or via package managers:**
  22. ```bash
  23. # Homebrew (Apple Silicon macOS + Linux)
  24. brew install dicklesworthstone/tap/cass
  25. # Windows (Scoop)
  26. scoop bucket add dicklesworthstone https://github.com/Dicklesworthstone/scoop-bucket
  27. scoop install dicklesworthstone/cass
  28. ```
  29. 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`.
  30. </div>
  31. ---
  32. ## 🤖 Agent Quickstart (Robot Mode)
  33. ⚠️ **Never run bare `cass` in an agent context** — it launches the interactive TUI. Always use `--robot` or `--json`.
  34. ```bash
  35. # 1) Check the installed interface once per version (recipe verified on 0.10.0).
  36. cass --version
  37. cass search --help
  38. # Verify a newly installed executable without opening the configured archive.
  39. cass selftest --json
  40. # `health --binary-only` still reports (and therefore probes) archive readiness.
  41. # 2) For a quick history question, start with scoped read-only lexical retrieval.
  42. # Hybrid remains the product default; lexical is explicit for this workflow.
  43. cass search "performance regression" --workspace /path/to/project --days 7 \
  44. --mode lexical --no-maintenance --robot --robot-meta --fields minimal \
  45. --limit 5 --max-tokens 2000 --timeout 2000
  46. # 3) Find the current or recent session for this workspace
  47. cass sessions --current --json
  48. cass sessions --workspace "$(pwd)" --json --limit 5
  49. # 4) View + expand a hit (use source_path/line_number from search output)
  50. cass view /path/to/session.jsonl -n 42 -C 3 --json --timeout 2000
  51. # 5) Discover the full machine API
  52. cass capabilities --json
  53. cass robot-docs guide
  54. cass robot-docs schemas
  55. # 6) Exclude a noisy agent harness from future indexing
  56. cass sources agents list --json
  57. cass sources agents exclude openclaw
  58. cass sources agents include openclaw
  59. ```
  60. The retrieval flags above are available in 0.8.0 and later. On older builds, check help;
  61. if `--no-maintenance` is absent, report the mismatch instead of dropping the
  62. read-only constraint. `--timeout` is in milliseconds, while `--max-tokens` limits
  63. approximate output size. Also set a caller-side deadline (for example, GNU
  64. `timeout 10s`); an externally interrupted command may leave incomplete JSON.
  65. Inspect `budget.timed_out` even after exit 0: timed-out empty hits are not proof
  66. that no history exists. A `maintenance-required` response ends the retrieval
  67. attempt; indexing or repair is a separate mutating task. Use triage/health/status
  68. for readiness diagnosis, not as repeated prerequisites to a short summary.
  69. Broaden scope deliberately, expand useful hits, and preserve source/line citations.
  70. `view -C` bounds context lines, not bytes; check excerpt size before including
  71. a long JSONL record in an agent prompt.
  72. **Output conventions**
  73. - stdout = data only
  74. - stderr = diagnostics
  75. - exit 0 = success
  76. **Search asset contract**
  77. - 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.
  78. - 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.
  79. - 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.
  80. - 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.
  81. - 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.
  82. - `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.
  83. **Lexical publish durability (atomic-swap)**
  84. - 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`.
  85. - 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.
  86. - 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.
  87. **Quarantine, GC, and the doctor/diag surface**
  88. - 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.
  89. - `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).
  90. - 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.
  91. - 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.
  92. **Schema stability guarantees**
  93. - 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`).
  94. - `cass introspect --json`'s `response_schemas` block enumerates every schema in a stable alphabetical order (`BTreeMap`-backed — see bead coding_agent_session_search-8sl73).
  95. - 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).
  96. ## 📬 Agent Mail Fallback (When MCP Tools Are Not Exposed)
  97. 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.
  98. ### 1) Start the local Agent Mail server
  99. ```bash
  100. ~/.local/pipx/venvs/mcp-agent-mail/bin/python -m mcp_agent_mail.cli serve-http --host 127.0.0.1 --port 8765
  101. ```
  102. ### 2) Use the Streamable HTTP MCP endpoint (`/mcp`)
  103. ```bash
  104. curl -sS -X POST http://127.0.0.1:8765/mcp \
  105. -H 'Content-Type: application/json' \
  106. -d '{"jsonrpc":"2.0","id":"health","method":"tools/call","params":{"name":"health_check","arguments":{}}}'
  107. ```
  108. ### 3) Minimal coordination flow (project -> agent -> message -> inbox -> ack)
  109. ```bash
  110. # Ensure project
  111. curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
  112. '{"jsonrpc":"2.0","id":"ensure","method":"tools/call","params":{"name":"ensure_project","arguments":{"human_key":"/data/projects/coding_agent_session_search"}}}'
  113. # Register agent
  114. curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
  115. '{"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"}}}'
  116. # Send message
  117. curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
  118. '{"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."}}}'
  119. # Fetch inbox
  120. curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
  121. '{"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}}}'
  122. # Acknowledge message id 42
  123. curl -sS -X POST http://127.0.0.1:8765/mcp -H 'Content-Type: application/json' -d \
  124. '{"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}}}}'
  125. ```
  126. ### Important caveat
  127. `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.
  128. ## 📸 Screenshots
  129. <div align="center">
  130. ### Search Results Across All Your Agents
  131. *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*
  132. <img src="docs/assets/screenshots/screenshot_01.webp" alt="Main TUI showing search results across multiple coding agents" width="800">
  133. ---
  134. ### Rich Conversation Detail View
  135. *Full conversation rendering with markdown formatting, code blocks, headers, and structured content*
  136. <img src="docs/assets/screenshots/screenshot_02.webp" alt="Detail view showing formatted conversation content" width="800">
  137. ---
  138. ### Quick Start & Keyboard Reference
  139. *Built-in help screen (press `F1` or `?`) with all shortcuts, filters, modes, and navigation tips*
  140. <img src="docs/assets/screenshots/screenshot_03.webp" alt="Help screen showing keyboard shortcuts and features" width="500">
  141. </div>
  142. ---
  143. ## 💡 Why This Exists
  144. ### The Problem
  145. 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**:
  146. - **Fragmented storage**: Each agent stores data differently—JSONL files, SQLite databases, markdown logs, proprietary JSON formats
  147. - **No cross-agent visibility**: Solutions discovered in Cursor are invisible when you're using Claude Code
  148. - **Lost context**: That brilliant debugging session from two weeks ago? Good luck finding it by scrolling through files
  149. - **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
  150. ### The Solution
  151. `cass` treats your coding agent history as a **unified knowledge base**. It:
  152. 1. **Normalizes** disparate formats into a common schema
  153. 2. **Indexes** everything with a purpose-built full-text search engine
  154. 3. **Surfaces** relevant past conversations in milliseconds
  155. 4. **Respects** your privacy—everything stays local, nothing phones home
  156. ### Who Benefits
  157. - **Individual developers**: Find that solution you know you've seen before
  158. - **Teams**: Share institutional knowledge across different tool preferences
  159. - **AI agents themselves**: Let your current agent learn from all your past agents (via robot mode)
  160. - **Power users**: Build workflows that leverage your complete coding history
  161. ---
  162. ## ✨ Key Features
  163. ### ⚡ Instant Search (Sub-60ms Latency)
  164. - **"Search-as-you-type"**: Results update instantly with every keystroke.
  165. - **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.
  166. - **Smart Tokenization**: Handles `snake_case` ("my_var" matches "my" and "var"), hyphenated terms, and code symbols (`c++`, `foo.bar`) correctly.
  167. - **Zero-Stall Updates**: The background indexer commits changes atomically; `reader.reload()` ensures new messages appear in the search bar immediately without restarting.
  168. - **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.
  169. ### 🧠 Optional Semantic Search (Local by Default)
  170. - **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.
  171. - **Warm-daemon reuse**: Semantic and hybrid CLI searches automatically use an
  172. already-running local embedding daemon (including a socket selected with
  173. `CASS_DAEMON_SOCKET`) and only initialize the installed in-process model if
  174. daemon inference fails. Pass `--daemon` to permit auto-spawning a missing
  175. daemon in human-mode searches (robot/JSON searches never spawn one, even
  176. with `--daemon`, because their bounded budget cannot wait for a daemon to
  177. start; start `cass daemon` yourself first; `_meta.effective.daemon` shows
  178. the request and what applied), or `--no-daemon` to force
  179. direct inference. `--fast-only` stays in
  180. the deterministic hash-vector space. Each data directory gets a distinct
  181. default socket and owner-private pinned key; fresh handshake, health,
  182. embedding, batch, and rerank challenges authenticate the exact response and
  183. immutable Frankensearch embedding identity before any daemon output is used.
  184. `--two-tier` progressive refinement (fast results refined in place by the
  185. quality tier) is experimental and currently inactive: the one-shot CLI
  186. collapses it to a single-tier quality search and the TUI's progressive lanes
  187. are disabled at HEAD, so hybrid search today is lexical plus one MiniLM
  188. refinement pass when the model is installed.
  189. - **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.
  190. - **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.
  191. - **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.
  192. - **Required files** (all must be present after install; `cass models verify --model <minilm|multilingual-minilm>` checks the selected model):
  193. - `model.safetensors`
  194. - `tokenizer.json`
  195. - `config.json`
  196. - `special_tokens_map.json`
  197. - `tokenizer_config.json`
  198. - **Vector index**: Stored as `vector_index/index-<embedder>.fsvi` in the data directory.
  199. - **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.
  200. #### Opt-In External Embeddings
  201. 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.
  202. 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:
  203. ```bash
  204. export CASS_EXTERNAL_EMBEDDINGS=1
  205. export CASS_EXTERNAL_EMBEDDING_URL='http://127.0.0.1:8000/v1/embeddings'
  206. export CASS_EXTERNAL_EMBEDDING_MODEL='your-model-name'
  207. export CASS_EXTERNAL_EMBEDDING_DIMENSION=384
  208. export CASS_EXTERNAL_EMBEDDING_REVISION='model-revision-1'
  209. # Set CASS_EXTERNAL_EMBEDDING_API_KEY separately if the service requires it.
  210. cass models backfill --tier quality --embedder external --data-dir /path/to/cass-data --json
  211. CASS_SEMANTIC_EMBEDDER=external cass search 'your query' --mode semantic --data-dir /path/to/cass-data --json
  212. ```
  213. 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.
  214. 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.
  215. #### Explicit Hash Vector Tier
  216. 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:
  217. | Feature | ML Model (MiniLM) | Hash Embedder (FNV-1a) |
  218. |---------|-------------------|------------------------|
  219. | **Meaning Understanding** | ✅ "car" ≈ "automobile" | ❌ Exact tokens only |
  220. | **Initialization Time** | ~500ms (model loading) | <1ms (instant) |
  221. | **Network Dependency** | None (after install) | None |
  222. | **Disk Footprint** | ~90MB model files | 0 bytes |
  223. | **Deterministic** | ✅ Same input = same output | ✅ Same input = same output |
  224. **Algorithm**:
  225. 1. **Tokenize**: Lowercase, split on non-alphanumeric, filter tokens <2 characters
  226. 2. **Hash**: Apply FNV-1a to each token
  227. 3. **Project**: Use hash to determine dimension index and sign (+1 or -1) in a 384-dimensional vector
  228. 4. **Normalize**: L2 normalize to unit length for cosine similarity
  229. **When to Use**:
  230. - Quick setup without downloading model files
  231. - Environments where ML inference overhead is unwanted
  232. - Fast-tier testing or an explicitly chosen degraded mode
  233. **Override**: Set `CASS_SEMANTIC_EMBEDDER=hash` to force hash mode even when ML model is available.
  234. #### FSVI Vector Index Format
  235. `cass` uses the **frankensearch FSVI** vector index format (`.fsvi`) for storing semantic embeddings.
  236. **Features**:
  237. - **Memory-mappable**: large indexes open without copying into RAM
  238. - **Quantization**: supports `f32` and `f16` storage for smaller on-disk size
  239. - **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
  240. **Index Location**: `~/.local/share/coding-agent-search/vector_index/index-<embedder>.fsvi`
  241. #### Search Modes
  242. `cass` supports three search modes, selectable via `--mode` flag or `Alt+S` in the TUI:
  243. | Mode | Algorithm | Best For |
  244. |------|-----------|----------|
  245. | **Lexical** | BM25 full-text | Exact term matching, code searches |
  246. | **Semantic** | Vector similarity | Conceptual queries, "find similar" |
  247. | **Hybrid** (default) | Lexical + single-tier semantic refinement fused with RRF; lexical fail-open | Balanced precision and recall |
  248. **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.
  249. **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.
  250. **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:
  251. ```
  252. RRF_score = Σ 1 / (K + rank_i)
  253. ```
  254. 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.
  255. ```bash
  256. # CLI examples
  257. cass search "authentication" --mode lexical --robot
  258. cass search "how to handle user login" --mode semantic --robot
  259. cass search "auth error handling" --mode hybrid --robot
  260. ```
  261. ### 🎯 Advanced Search Features
  262. - **Wildcard Patterns**: Full glob-style pattern support:
  263. - `foo*` - Prefix match (finds "foobar", "foo123")
  264. - `*foo` - Suffix match (finds "barfoo", "configfoo")
  265. - `*foo*` - Substring match (finds "afoob", "configuration")
  266. - **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.
  267. - **Query History Deduplication**: Recent searches deduplicated to show unique queries; navigate with `Up`/`Down` arrows.
  268. - **Match Quality Ranking**: New ranking mode (cycle with `F12`) that prioritizes exact matches over wildcard/fuzzy results.
  269. - **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.
  270. ### 🖥️ Rich Terminal UI (TUI)
  271. 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.
  272. - **Three-Pane Layout**: Filter bar (top), scrollable results (left), and syntax-highlighted details (right).
  273. - **Multi-Line Result Display**: Each result shows location and up to 3 lines of context; alternating stripes improve scanability.
  274. - **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.
  275. - **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).
  276. - **Find-in-Detail**: Press `/` to search within the detail pane; matches highlighted with `n`/`N` navigation.
  277. - **Mouse Support**: Click to select results, scroll panes, or clear filters.
  278. - **Theming**: Adaptive Dark/Light modes with role-colored messages (User/Assistant/System). Presets include dark, light, high-contrast, and accessible variants.
  279. - **Ranking Modes**: Cycle through `recent`/`balanced`/`relevance`/`quality` with `F12`; quality mode penalizes fuzzy matches.
  280. - **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.
  281. - **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`.
  282. - **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.
  283. - **Asciicast Recording**: Capture reproducible TUI demos and bug repro artifacts with `cass tui --asciicast demo.cast`.
  284. - Security default: recording captures terminal output only (input keystrokes are not serialized by default).
  285. ### 📄 HTML Session Export
  286. Export conversations as styled, portable HTML files with optional encryption:
  287. - **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.
  288. - **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.
  289. - **Password Protection**: AES-256-GCM encryption with PBKDF2 key derivation (600,000 iterations)—opens directly in any browser
  290. - **Rich Styling**: Dark/light themes, syntax-highlighted code blocks, collapsible tool calls
  291. - **Print-Friendly**: Optimized print styles with page breaks and footers
  292. - **Searchable**: Built-in search functionality within the exported document
  293. - **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.
  294. **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.
  295. **CLI Usage**:
  296. ```bash
  297. # Basic export
  298. cass export-html /path/to/session.jsonl
  299. # With encryption
  300. printf '%s\n' "secret" | cass export-html /path/to/session.jsonl --encrypt --password-stdin
  301. # Explicit raw-fidelity export (contains credentials; handle as sensitive)
  302. cass export-html /path/to/session.jsonl --include-secrets --json
  303. # Custom output location
  304. cass export-html session.jsonl --output-dir ~/exports --filename "my-session"
  305. # Open in browser after export
  306. cass export-html session.jsonl --open
  307. # Robot mode (JSON output)
  308. cass export-html session.jsonl --json
  309. ```
  310. ### 🔗 Universal Connectors
  311. 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):
  312. - **Codex**: `~/.codex/sessions` and `~/.codex/archived_sessions` (Rollout JSONL, plain or zstd-compressed `.jsonl.zst`)
  313. - **Cline**: VS Code global storage (Task directories)
  314. - **Gemini CLI**: `~/.gemini/tmp` (Chat JSON)
  315. - **Claude Code**: `~/.claude/projects` (Session JSONL), plus macOS Desktop metadata sidecars under
  316. `~/Library/Application Support/Claude/claude-code-sessions` and
  317. `~/Library/Application Support/Claude/local-agent-mode-sessions`
  318. - **Clawdbot**: `~/.clawdbot/sessions` (Session JSONL)
  319. - **Vibe (Mistral)**: `~/.vibe/logs/session/*/messages.jsonl` (Session JSONL)
  320. - **OpenCode**: `.opencode` directories (SQLite)
  321. - **Amp**: `~/.local/share/amp` & VS Code storage
  322. - **Cursor**: `~/Library/Application Support/Cursor/User/` global + workspace storage (SQLite `state.vscdb`)
  323. - **ChatGPT**: `~/Library/Application Support/com.openai.chat` (v1 unencrypted JSON; v2/v3 encrypted—see Environment)
  324. - **Aider**: `~/.aider.chat.history.md` and per-project `.aider.chat.history.md` files (Markdown)
  325. - **Pi-Agent**: `~/.pi/agent/sessions` (Session JSONL with thinking content; `pi_agent_rust` SQLite sessions too)
  326. - **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
  327. - **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.
  328. - **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)
  329. - **GitHub Copilot Chat**: VS Code global storage under `github.copilot-chat` (JSON)
  330. - **Copilot CLI**: `~/.copilot/session-state`, legacy `~/.copilot/history-session-state`, and `gh copilot` config paths (JSONL/JSON)
  331. - **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.
  332. - **Goose**: `~/.local/share/goose/sessions/sessions.db` (SQLite, v1.20+), plus the earlier per-session `*.jsonl` layout under `~/.goose/sessions`
  333. - **Crush**: `~/.crush/crush.db` and per-project `.crush/crush.db` (SQLite)
  334. - **Hermes**: `~/.hermes/state.db` and project-local `.hermes/state.db` (SQLite)
  335. - **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.
  336. - **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.
  337. - **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.
  338. - **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)
  339. - **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`)
  340. - **Qwen Code**: `~/.qwen/tmp/*/chats/session-*.json` (Chat JSON)
  341. - **Factory (Droid)**: `~/.factory/sessions` (JSONL files organized by workspace slug)
  342. - **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>`).
  343. - **OpenHands (OpenDevin)**: `~/.openhands/conversations/<id>/` — `base_state.json` metadata plus an `events/event-NNNNN-<uuid>.json` event stream (JSON)
  344. - **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>`.
  345. - **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.
  346. - **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.
  347. - **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.
  348. Claude Code Desktop sidecars preserve title, workspace, model, and session IDs,
  349. but not necessarily the full conversation body. If Claude Code has culled an old
  350. CLI JSONL body, cass can still index searchable sidecar metadata while reporting
  351. that the conversation body is unavailable.
  352. #### Connector Details
  353. **Pi-Agent** parses JSONL session files with rich event structure:
  354. - **Location**: `~/.pi/agent/sessions/` (override the agent home with `PI_CODING_AGENT_DIR`, or the sessions directory directly with `PI_SESSIONS_DIR`)
  355. - **Format**: Typed events—`session_start`, `message`, `model_change`, `thinking_level_change`
  356. - **Features**: Extracts extended thinking content, flattens tool calls with arguments, tracks model changes
  357. - **Detection**: Scans for `*_*.jsonl` pattern in sessions directory
  358. **Oh My Pi (`omp`)** uses the same pi-family wire format but remains a separate
  359. agent identity throughout search, analytics, resume, TUI, and HTML export:
  360. - **Default and profiles**: `~/.omp/agent/sessions/` and `~/.omp/profiles/<name>/agent/sessions/`; `OMP_PROFILE` selects a profile and takes precedence over legacy `PI_PROFILE`
  361. - **XDG**: `$XDG_DATA_HOME/omp/sessions/` and `$XDG_DATA_HOME/omp/profiles/<name>/sessions/` when the OMP XDG root exists
  362. - **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.
  363. - **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
  364. - **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.
  365. **OpenCode** reads SQLite databases from workspace directories:
  366. - **Location**: `.opencode/` directories (scans recursively from home)
  367. - **Format**: SQLite database with sessions table
  368. - **Detection**: Finds directories named `.opencode` containing database files
  369. ### 🌐 Remote Sources (Multi-Machine Search)
  370. 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.
  371. #### Interactive Setup Wizard (Recommended)
  372. The easiest way to configure multi-machine search is the interactive setup wizard:
  373. ```bash
  374. cass sources setup
  375. ```
  376. **What the wizard does:**
  377. 1. **Discovers** SSH hosts from your `~/.ssh/config`
  378. 2. **Probes** each host to check for:
  379. - Existing cass installation (and version)
  380. - Agent session data (Claude, Codex, Cursor, Gemini, etc.)
  381. - System resources (disk space, memory)
  382. 3. **Lets you select** which hosts to configure
  383. 4. **Installs cass** on remotes that don't have it (optional)
  384. 5. **Indexes** existing sessions on remotes (optional)
  385. 6. **Configures** `sources.toml` with correct paths and mappings
  386. 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)
  387. **Wizard options:**
  388. | Flag | Purpose |
  389. |------|---------|
  390. | `--hosts <names>` | Configure only specific hosts (comma-separated) |
  391. | `--dry-run` | Preview changes without applying them |
  392. | `--non-interactive` | Use auto-detected defaults for scripting |
  393. | `--skip-install` | Don't install cass on remotes |
  394. | `--skip-index` | Don't run indexing on remotes |
  395. | `--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 |
  396. | `--resume` | Resume an interrupted setup |
  397. | `--json` | Output progress as JSON (for automation) |
  398. **Examples:**
  399. ```bash
  400. # Full interactive wizard
  401. cass sources setup
  402. # Configure specific hosts only
  403. cass sources setup --hosts laptop,workstation,build-server
  404. # Preview without making changes
  405. cass sources setup --dry-run
  406. # Resume interrupted setup
  407. cass sources setup --resume
  408. # Non-interactive for CI/CD
  409. cass sources setup --non-interactive --hosts myserver --skip-install
  410. ```
  411. **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`.
  412. #### Testing your real fleet
  413. Tailscale discovery is optional: `cass sources discover --tailscale --json` adds
  414. online tailnet peers to SSH-config discovery, and `cass sources setup --tailscale`
  415. offers them in setup. It reads local `tailscale status --json` with a five-second
  416. deadline; a missing CLI, stopped daemon, or login failure produces a warning and
  417. leaves SSH-config discovery available. Explicit `setup --hosts` skips discovery.
  418. Connections use ordinary SSH over assigned Tailscale IPv4 addresses, so MagicDNS
  419. is not required. Matching SSH aliases retain their user/key configuration;
  420. otherwise SSH uses its normal defaults. IPv6-only peers are currently omitted.
  421. Tailscale ACLs, SSH authorization and host-key checks still apply; discovery does
  422. not log in, install Tailscale, or change either SSH or tailnet configuration.
  423. The local fixture and Docker tests do not prove that your machines can sync and
  424. search each other's sessions. The opt-in live harness uses actual SSH connections
  425. and `cass sources discover`, `sources add`, `sources sync`, and `search`. It creates isolated synthetic
  426. Codex sessions on each machine, checks source provenance and filters, repeats a
  427. sync to detect duplicates, and appends messages. It checks both lexical and default
  428. hybrid search, requires one JSON response per sync, holds the real indexing lock to
  429. test busy refusal, and recovers transferred sessions through `sources reingest`.
  430. A refused SSH connection must leave the other sources searchable.
  431. Keep the inventory and SSH configuration **outside this repository**. For example,
  432. create a mode-0600 JSON file containing:
  433. ```json
  434. {
  435. "ssh_config": "/private/path/to/ssh_config",
  436. "hosts": [{"ssh": "workstation"}, {"ssh": "laptop"}]
  437. }
  438. ```
  439. Then run with an explicit binary:
  440. ```bash
  441. python3 scripts/e2e/live_fleet_search.py \
  442. --inventory /private/path/to/fleet.json \
  443. --cass-bin /path/to/cass
  444. ```
  445. Python 3 and authenticated SSH access are required on the remote machines.
  446. The Unix runner needs Python 3.9+, rsync, and a CASS binary supporting the tested
  447. commands. Each inventory alias must appear in the supplied SSH configuration;
  448. included configuration files are supported. Host-key verification stays enabled.
  449. To exercise actual tailnet discovery and transport, add `--tailscale` to the
  450. harness command and use tailnet IPv4 addresses as the private inventory targets.
  451. Keep any required SSH users, keys and trusted host-key aliases in the private SSH
  452. configuration. For a discovery test independent of explicit aliases, use SSH
  453. `Match originalhost` entries rather than literal `Host` entries for those addresses.
  454. The harness retains fresh test directories and raw
  455. receipts privately outside git; it never changes existing session archives or
  456. deletes test data. Console results use ordinal labels. An unreachable machine
  457. keeps the overall result failed, even if the other machines pass. Do not attach
  458. raw receipts or inventories to public issues: they contain machine identities.
  459. #### Remote Installation Methods
  460. 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:
  461. | Priority | Method | Speed | Requirements |
  462. |----------|--------|-------|--------------|
  463. | 1 | **Pre-built binary** | ~10s | curl/wget, GitHub access, compatible release binary |
  464. | 2 | **Source build** | ~30 min | rustup and cargo, curl/wget, 6GB free disk in `$HOME`, 10GB RAM |
  465. | 3 | **Full bootstrap** | ~30 min | curl, 6GB free disk in `$HOME`, 10GB RAM (installs rustup, then builds as in 2) |
  466. The source build does what `install.sh --from-source` does: it downloads the
  467. release tag's source archive into `$HOME`, installs the Rust toolchain that
  468. tag's `rust-toolchain.toml` pins (a dated nightly; cass does not build on
  469. stable), and runs `cargo install --locked --path . --bin cass` inside it, so the
  470. binary lands in `~/.cargo/bin/cass`. The unpacked tree is removed afterwards. It
  471. does not use crates.io. It builds with thin LTO instead of the release
  472. profile's fat LTO, so the binary is somewhat larger and slower than the
  473. published one. Measured building v0.10.0 on a fresh account (two build jobs):
  474. 28 minutes, 8.6 GB peak compiler memory (10.9 GB and 36 minutes with fat LTO),
  475. 1.5 GB toolchain, 0.8 GB cargo cache and a 2.6 GB build tree. The wizard
  476. offers it only to hosts above those floors.
  477. > **crates.io lags the releases:** the newest version on crates.io is 0.7.0
  478. > (2026-08-25), so `cargo install coding-agent-search` builds 0.7.0. Later
  479. > versions depend on `franken-agent-detection` and `frankensearch` at exact git
  480. > revisions. Their required APIs must be published before CASS can return to
  481. > registry-only dependencies (bead zztql; GH #548). Use the installer or the
  482. > GitHub Release binaries for a
  483. > current version.
  484. **Resource Requirements**:
  485. - Minimum 1GB free disk in `$HOME` for the pre-built binary
  486. - 6GB free disk in `$HOME` and 10GB RAM for a source build
  487. - 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.
  488. - SSH access with key-based authentication
  489. **What Gets Installed**:
  490. - The `cass` binary (location depends on method: `~/.cargo/bin/cass` for cargo-based, `~/.local/bin/cass` for pre-built binary)
  491. - No daemon, no background services—just the binary
  492. **Installation Progress**: The wizard shows real-time progress for each stage:
  493. ```
  494. Installing cass on laptop...
  495. [1/4] Checking environment... ✓
  496. [2/4] Downloading binary... ████████░░ 80%
  497. [3/4] Verifying checksum... ✓
  498. [4/4] Setting up PATH... ✓
  499. ```
  500. Use `--skip-install` if you prefer to install manually on remotes.
  501. #### Host Discovery & Probing
  502. The setup wizard automatically discovers SSH hosts from your configuration:
  503. **Discovery Sources**:
  504. - `~/.ssh/config` (parses Host entries)
  505. - Hosts with wildcards (`*`, `?`) are automatically excluded
  506. **Probe Results** (for each discovered host):
  507. | Check | Purpose |
  508. |-------|---------|
  509. | **Connectivity** | Can we establish SSH connection? |
  510. | **cass Version** | Is cass already installed? What version? |
  511. | **Agent Data** | Which agents have session data? |
  512. | **Session Count** | How many conversations exist? |
  513. | **System Info** | OS, architecture, disk space, memory |
  514. Each setup run probes every selected host afresh; probe results are not cached between runs.
  515. #### Manual Setup
  516. For manual configuration without the wizard:
  517. ```bash
  518. # Add a remote machine using platform presets
  519. cass sources add user@laptop.local --preset macos-defaults
  520. # Or specify paths explicitly
  521. cass sources add dev@workstation --path ~/.claude/projects --path ~/.codex/sessions
  522. # Sync sessions from all configured sources
  523. cass sources sync
  524. # Check source health and connectivity
  525. cass sources doctor
  526. ```
  527. #### Remote Archive Safety
  528. Remote source diagnostics are intentionally local-only. `cass triage --json`,
  529. `cass doctor --json`, `cass health --json`, and `cass status --json` report the
  530. `remote_source_sync` summary from cass-owned evidence: `sources.toml`,
  531. `sync_status.json`, the local `remotes/<source>/mirror/` copy, and archive DB
  532. provenance rows. They do not open SSH sessions, mutate remote machines, or
  533. rewrite provider session logs while classifying source gaps.
  534. `cass sources doctor` is the explicit networked exception: it performs bounded,
  535. read-only probes of configured source hosts. Its per-source human summary keeps
  536. the same native reachability, binary-health, and mirror/sync state codes and
  537. safe command as the JSON report. It intentionally does not claim local search
  538. readiness, because a remote host probe cannot establish the controller's local
  539. SQLite, lexical, or semantic asset state.
  540. This matters because agent harnesses can prune their own logs. If a laptop is
  541. retired, a remote path disappears, or a provider truncates older sessions, the
  542. cass archive DB and cass-owned local mirror may be the only remaining evidence
  543. for those conversations. Treat gap names such as `remote_source_unavailable`,
  544. `remote_source_pruned`, `local_archive_ahead_of_remote`, and
  545. `remote_copy_ahead_verified` as preservation signals first: keep the archive and
  546. mirror intact, then run the recommended `cass sources sync --json` (all configured remote sources; `--source <name>` narrows it) or
  547. source-specific sync command after reviewing the reported evidence.
  548. Raw-mirror retention is explicit and audited. Use `cass mirror prune
  549. --older-than 90d --json` or `cass mirror prune --max-size 100GB --json` to get a
  550. dry-run plan; add `--apply` only after reviewing the scope and totals. Preview
  551. `entries` contain at most 1,000 manifest/blob details; `omitted_entry_count`
  552. reports additional candidates. Planned counts and bytes cover the entire plan,
  553. including omitted details. Use provider/path selectors to inspect a narrower
  554. scope. Previews do not append audit records. Add
  555. `--keep-tag <tag>` to pin captures linked to tagged conversations. `prune`
  556. holds down blobs referenced by captures from the last 7 days by default, writes
  557. complete intent/result records to `raw-mirror/v1/pruned.jsonl` for non-empty
  558. applied plans, and refuses apply mode
  559. while an index/watch job is active.
  560. Applied pruning syncs the audit independently of the optional capture setting
  561. `CASS_RAW_MIRROR_FSYNC`. Each completed result is recorded before the next
  562. removal; a later failure preserves those earlier results. An abrupt crash
  563. between a removal and its result record can still leave an intent without a
  564. confirmed result.
  565. Use `--provider opencode` and/or `--source-path '*/opencode.db'` with an age
  566. or size rule to target one source without retiring unrelated captures.
  567. Repeated providers are alternatives; a source-path glob further narrows them.
  568. `--keep-latest N` retires every capture of a source file except its newest N
  569. (a source file is one provider, source and original path) and keeps those N
  570. out of reach of `--older-than` and `--max-size`. Use it for a prune that runs
  571. on a timer: `cass mirror prune --keep-latest 1 --safety-hold-down 6h --apply`
  572. keeps the mirror to the newest capture of each source file plus whatever was
  573. captured inside the hold-down window, and never retires the only copy of a
  574. session whose provider has since deleted it. Older captures of an appended
  575. transcript share their complete chunks with the newest one, so retiring them
  576. frees only their superseded tail chunks; for a file that was rewritten rather
  577. than appended to, it also drops the earlier versions.
  578. A capture stages its copy under `raw-mirror/v1/tmp/capture.<pid>.<ts>.<n>` and
  579. holds the mirror lock until it publishes. A capture that is killed, for example
  580. by a `timeout` around `cass index`, leaves that directory behind. An unscoped
  581. `cass mirror prune` (no `--provider` or `--source-path`) takes the same lock, so
  582. any staging directory it finds is abandoned. The preview lists each one that
  583. has not been written for an hour, with its size, as a `staging` entry, and
  584. `--apply` removes it. Staging-named symlinks are not followed.
  585. A pruned capture of a source that is still on disk is copied again by the next
  586. index run. On a machine whose providers never delete their session files, set
  587. `CASS_RAW_MIRROR=0` (or `false`, `no`, `off`) to stop capturing altogether.
  588. Indexing and search are unchanged, and existing captures stay until you prune
  589. them. `cass doctor` reports `raw_mirror_capture_disabled` and warns about what is
  590. given up: a session file its provider later deletes survives only in the
  591. archive DB.
  592. With a selector, `--max-size` measures unique blobs in that selection. Shared
  593. blobs still referenced outside it and orphan blobs without source provenance
  594. remain protected. The JSON plan records the selectors and `scope_blob_bytes`.
  595. Large mutable sources are stored as content-addressed chunks: JSONL and
  596. NDJSON transcripts of 256 KiB or more in 256 KiB chunks, and other sources of
  597. 8 MiB or more, such as SQLite stores, in 4 MiB chunks. A growing transcript
  598. reuses every unchanged complete chunk, so an index run after an append stores
  599. only its changed tail chunk and a manifest, and SQLite sources reuse unchanged
  600. 4 MiB byte regions. Each historical snapshot remains byte-exact without
  601. writing another full-file blob. Existing whole-blob manifests remain readable;
  602. `cass doctor --json` reports `storage_kind`, `chunk_count`, the full-source
  603. digest, and verifies every referenced chunk before treating a snapshot as
  604. recovery authority.
  605. #### Configuration File
  606. Sources are configured in the platform config directory (Linux: `~/.config/cass/sources.toml`, macOS: `~/Library/Application Support/cass/sources.toml`):
  607. ```toml
  608. [[sources]]
  609. name = "laptop"
  610. type = "ssh"
  611. host = "user@laptop.local"
  612. paths = ["~/.claude/projects", "~/.codex/sessions"]
  613. sync_schedule = "manual"
  614. [[sources]]
  615. name = "workstation"
  616. type = "ssh"
  617. host = "dev@work.example.com"
  618. paths = ["~/.claude/projects"]
  619. sync_schedule = "daily"
  620. # Path mappings rewrite remote paths to local equivalents
  621. [[sources.path_mappings]]
  622. from = "/home/dev/projects"
  623. to = "/Users/me/projects"
  624. # Agent-specific mappings
  625. [[sources.path_mappings]]
  626. from = "/opt/work"
  627. to = "/Volumes/Work"
  628. agents = ["claude_code"]
  629. ```
  630. **Configuration Fields:**
  631. | Field | Description |
  632. |-------|-------------|
  633. | `name` | Friendly identifier (becomes `source_id`) |
  634. | `type` | Connection type: `ssh` or `local` |
  635. | `host` | SSH host (`user@hostname`) |
  636. | `paths` | Paths to sync (supports `~` expansion) |
  637. | `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` |
  638. | `path_mappings` | Rewrite remote paths to local equivalents |
  639. #### CLI Commands
  640. ```bash
  641. # List configured sources
  642. cass sources list [--verbose] [--json]
  643. # Add a new source
  644. cass sources add <user@host> [--name <name>] [--preset macos-defaults|linux-defaults] [--path <path>...] [--no-test] [--json]
  645. # Set how often `cass schedule install` jobs sync a remote source (default: manual)
  646. cass sources schedule <name> <manual|hourly|daily> [--json]
  647. # Remove a source
  648. cass sources remove <name> [--purge] [-y]
  649. # Check connectivity and config
  650. cass sources doctor [--source <name>] [--json]
  651. # Sync sessions
  652. cass sources sync [--source <name>] [--no-index] [--verbose] [--dry-run] [--json]
  653. ```
  654. #### Read-Only (rrsync) Remotes
  655. 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:
  656. - Write remote paths without `~`. cass expands `~` by asking the remote shell for `$HOME`, and rrsync refuses that.
  657. - 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.
  658. - 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.
  659. #### Excluding Noisy Agent Harnesses
  660. If one harness is generating mostly junk or looped output, you can disable it persistently even if its files remain on disk:
  661. ```bash
  662. # Inspect current include/exclude state
  663. cass sources agents list --json
  664. # Stop indexing this harness in future runs
  665. cass sources agents exclude openclaw
  666. # Re-enable it later
  667. cass sources agents include openclaw
  668. ```
  669. `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.
  670. 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.
  671. 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.
  672. 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.
  673. If you want to block future indexing but keep the data already archived:
  674. ```bash
  675. cass sources agents exclude openclaw --keep-indexed-data
  676. ```
  677. 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.
  678. #### Sync Engine Internals
  679. The sync engine uses rsync over SSH for efficient delta transfers and falls back to other transports when rsync is unavailable:
  680. **Transfer Methods** (auto-detected):
  681. | Method | When Used | Characteristics |
  682. |--------|-----------|-----------------|
  683. | **rsync** | rsync available on both ends | Delta transfers, compression, progress stats |
  684. | **WSL rsync** | Windows without native rsync, WSL with rsync installed | Runs `wsl rsync` |
  685. | **scp** | rsync unavailable | Full file copies through the system `scp`, inheriting the OpenSSH agent, keys and `~/.ssh/config` |
  686. | **SFTP** | the fallbacks above unavailable | Full file transfers via the SSH native protocol |
  687. **Safety Guarantees**:
  688. - **Additive-only syncs**: rsync runs WITHOUT `--delete`, so remote deletions never propagate locally.
  689. - **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.
  690. - **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.
  691. **Transfer Configuration**:
  692. | Setting | Default | Purpose |
  693. |---------|---------|---------|
  694. | Connection timeout | 10s | Fail fast on unreachable hosts |
  695. | 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 |
  696. | Compression | Enabled | Reduce bandwidth for text-heavy sessions |
  697. | Partial transfers | Enabled | Resume interrupted syncs |
  698. **rsync Flags Used**:
  699. ```
  700. -avz --links --safe-links --stats --partial [--protect-args | --secluded-args] --timeout 300 \
  701. -e "ssh [-F $CASS_SSH_CONFIG] -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=yes"
  702. ```
  703. 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.
  704. **Data Flow**:
  705. ```
  706. Remote: ~/.claude/projects/
  707. ↓ (rsync over SSH)
  708. Local: ~/.local/share/coding-agent-search/remotes/<source>/mirror/<path>_<hash>/
  709. ↓ (connector scan)
  710. Index: agent_search.db + index/v9-quill/
  711. ```
  712. 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.
  713. Sessions from remotes are indexed alongside local sessions, with provenance tracking to identify origin.
  714. #### Path Mappings
  715. 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:
  716. ```bash
  717. # List current mappings
  718. cass sources mappings list laptop
  719. # Add a mapping
  720. cass sources mappings add laptop --from /home/user/projects --to /Users/me/projects
  721. # Test how a path would be rewritten
  722. cass sources mappings test laptop /home/user/projects/myapp/src/main.rs
  723. # Output: /Users/me/projects/myapp/src/main.rs
  724. # Agent-specific mappings (only apply for certain agents)
  725. cass sources mappings add laptop --from /opt/work --to /Volumes/Work --agents claude_code,codex
  726. # Remove a mapping by index
  727. cass sources mappings remove laptop 0
  728. ```
  729. #### TUI Source Filtering
  730. In the TUI, filter sessions by origin:
  731. - **F11**: Cycle source filter (all → local → remote → all)
  732. - **Shift+F11**: Open source filter menu to select specific sources
  733. Remote sessions display with a source indicator (e.g., `[laptop]`) in the results list.
  734. #### Provenance Tracking
  735. Each conversation tracks its origin:
  736. - `source_id`: Machine identifier (e.g., "laptop", "workstation")
  737. - `origin_kind`: `local` or `remote`
  738. - `origin_host`: the remote host label, absent for local sessions
  739. - `workspace_original`: Original path on the remote machine (before path mapping)
  740. `--fields provenance` selects exactly `source_id`, `origin_kind` and `origin_host`.
  741. These fields appear in JSON/robot output and enable filtering:
  742. ```bash
  743. cass search "auth error" --source laptop --json
  744. cass timeline --since 7d --source remote
  745. cass stats --by-source
  746. ```
  747. ## 🤖 AI / Automation Mode
  748. `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.
  749. ### Why Cross-Agent Search Matters
  750. Imagine you're Claude Code working on a React authentication bug. With `cass`, you can instantly search across:
  751. - Your own previous sessions where you solved similar auth issues
  752. - Codex sessions where someone debugged OAuth flows
  753. - Cursor conversations about token refresh patterns
  754. - Aider chats about security best practices
  755. 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.
  756. ### Self-Documenting API
  757. `cass` teaches agents how to use it—no external documentation required:
  758. ```bash
  759. # First-stop capability contract for agents
  760. cass triage --json
  761. cass capabilities --json
  762. # → {"version": "...", "workflows": [...], "mistake_recoveries": [...], "commands": [...], "exit_codes": [...], "env_vars": [...]}
  763. # Full API schema with argument types, defaults, and response shapes
  764. cass introspect --json
  765. # Topic-based help optimized for LLM consumption
  766. cass robot-docs commands # All commands and flags
  767. cass robot-docs schemas # Response JSON schemas
  768. cass robot-docs examples # Copy-paste invocations
  769. cass robot-docs exit-codes # Error handling guide
  770. cass robot-docs guide # Quick-start walkthrough
  771. ```
  772. ### Forgiving Syntax (Agent-Friendly Parsing)
  773. AI agents sometimes make syntax mistakes. `cass` aggressively normalizes input to maximize acceptance when intent is clear:
  774. | What you type | What `cass` understands | Correction note |
  775. |---------------|------------------------|-----------------|
  776. | `cass -robot --limit=5` | `cass --robot --limit=5` | Single-dash long flags normalized |
  777. | `cass --Robot --LIMIT 5` | `cass --robot --limit 5` | Case normalized |
  778. | `cass search "auth" --max_results 5` | `cass search "auth" --limit 5` | Snake-case long flag normalized before alias recovery |
  779. | `cass find "auth"` | `cass search "auth"` | `find`/`query`/`q` → `search` via alias table |
  780. | `cass --robot-docs` | `cass robot-docs` | Flag-as-subcommand detected |
  781. | `cass commands --json` | `cass robot-docs commands` | Robot-docs topic shorthand detected |
  782. | `cass schemas --json` | `cass robot-docs schemas` | Robot-docs topic shorthand detected |
  783. | `cass ready --json` | `cass triage --json` | One-shot triage alias |
  784. | `cass preflight --json` | `cass triage --json` | One-shot triage alias |
  785. | `cass --json` | `cass triage --json` | Top-level robot request defaults to safe preflight |
  786. | `cass --robot` | `cass triage --json` | Top-level robot request defaults to safe preflight |
  787. | `cass --json search "auth"` | `cass search "auth" --json` | Leading structured flag moved to the robot-capable subcommand |
  788. | `cass --robot status` | `cass status --json` | Leading robot flag canonicalized to JSON output |
  789. | `cass answer "auth" --json` | `cass pack "auth" --json` | Cited-handoff aliases normalized to answer pack |
  790. | `cass why auth failed --json --max-evidence 3` | `cass pack "auth failed" --json --max-evidence 3` | Question/RC prompt aliases normalized to answer pack |
  791. | `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 |
  792. | `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 |
  793. | `cass html-export session.jsonl --json` | `cass export-html session.jsonl --json` | Reversed HTML export aliases normalized to the archive exporter |
  794. | `cass current --json` | `cass sessions --current --json` | Current-session shorthand normalized to session discovery |
  795. | `cass sessions current --json` | `cass sessions --current --json` | Positional `current` accepted as the sessions current flag |
  796. | `cass search --query "auth" --json` | `cass search "auth" --json` | Named query option converted to required positional query |
  797. | `cass search --q "auth" --json` | `cass search "auth" --json` | Short/familiar query aliases converted to required positional query |
  798. | `cass search auth error --json` | `cass search "auth error" --json` | Adjacent unquoted query words folded into one search |
  799. | `cass auth error --json` | `cass search "auth error" --json` | Unquoted robot-mode query words folded into search |
  800. | `cass search --agent codex --limit 5 auth error --json` | `cass search "auth error" --agent codex --limit 5 --json` | Query moved before leading search filters |
  801. | `cass view --path session.jsonl --line 42 --json` | `cass view session.jsonl --line 42 --json` | Named path option converted to required positional path |
  802. | `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 |
  803. | `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 |
  804. | `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) |
  805. | `cass search "auth" --format json` | `cass search "auth" --robot-format json` | Familiar format spelling converted to robot format |
  806. | `cass search "auth" --output json` | `cass search "auth" --robot-format json` | Familiar output spelling converted to robot format |
  807. | `cass help search --json` | `cass robot-docs commands` | Structured help intent routed to the machine-readable command reference |
  808. | `cass --format json status` | `cass status --robot-format json` | Leading format request moved to the target subcommand |
  809. | `cass search "auth" --max-results 5` | `cass search "auth" --limit 5` | Result-count alias converted to canonical limit |
  810. | `cass search "auth" -n 5` | `cass search "auth" --limit 5` | Familiar short count flag converted to canonical limit |
  811. | `cass search "auth" --last 7 --before now` | `cass search "auth" --since -7d --until now` | Familiar time-window aliases converted to canonical filters |
  812. | `cass search "auth" last=7d before=now` | `cass search "auth" --since -7d --until now` | Bare time-window assignments converted to canonical filters |
  813. | `cass search "auth" --provider codex` | `cass search "auth" --agent codex` | Provider/tool/connector aliases converted to canonical agent filter |
  814. | `cass search "auth" provider=codex` | `cass search "auth" --agent codex` | Bare provider assignment converted to canonical agent filter |
  815. | `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 |
  816. | `cass search --limt 5` | `cass search --limit 5` | Flag typos within Levenshtein distance ≤2 corrected |
  817. The CLI applies multiple normalization layers:
  818. 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.
  819. 2. **Case normalization**: `--Robot`, `--LIMIT` → `--robot`, `--limit`
  820. 3. **Snake-case flag recovery**: `--max_results`, `--data_dir`, and other known snake_case long flags become canonical kebab-case before alias recovery runs
  821. 4. **Single-dash recovery**: `-robot` → `--robot` (common LLM mistake)
  822. 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`
  823. 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.
  824. 7. **Root robot default**: `cass --json`, `cass --robot`, or `cass --robot-format json` with no subcommand runs read-only `triage`
  825. 8. **Leading structured flag recovery**: `--json`/`--robot` before a robot-capable subcommand is moved onto that subcommand
  826. 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
  827. 10. **Multi-word query recovery**: adjacent unquoted query words after `search`/`pack` become one query positional
  828. 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
  829. 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
  830. 13. **Result-count aliases**: `--max-results`, `--num-results`, `--results`, `--count`, `--top-k`, and `-n` become `--limit` on commands with result limits
  831. 14. **Time-window aliases**: `--last 7`, `--before now`, `last=7d`, and `before=now` become canonical `--since`/`--until` filters
  832. 15. **Provider aliases**: `--provider`, `--tool`, `--connector`, and matching assignments become canonical `--agent` filters on search-like commands
  833. 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
  834. 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`
  835. 18. **Drill-down line aliases**: `--line-number`, `--line_number` and `line=42` become `--line` (a raw file line)
  836. 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
  837. 20. **Leading-filter query recovery**: if a search/pack query comes after leading options, the query is moved back to the required positional slot
  838. 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
  839. 22. **Current-session shorthand**: `current`, `current-session`, and `sessions current` become `sessions --current`
  840. 23. **Global flag hoisting**: Position-independent flag handling
  841. 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`.
  842. ### Structured Output Formats
  843. Every command supports machine-readable output:
  844. ```bash
  845. # Pretty-printed JSON (default robot mode)
  846. cass search "error" --robot
  847. # Streaming JSONL: one hit per line. Add --robot-meta to prepend a
  848. # {budget, _meta} header line (elapsed_ms, next_cursor, state, index_freshness).
  849. # The header also appears without --robot-meta when the search timed out
  850. # (budget.timed_out), returned did-you-mean suggestions, --aggregate or --explain.
  851. cass search "error" --robot-format jsonl # hits only
  852. cass search "error" --robot-format jsonl --robot-meta # 1 _meta header + hits
  853. # Compact single-line JSON (minimal bytes)
  854. cass search "error" --robot-format compact
  855. # Include performance metadata
  856. cass search "error" --robot --robot-meta
  857. # → { "hits": [...], "_meta": { "elapsed_ms": 12, "cache_hit": true, "wildcard_fallback": false, "lexical_degrade_reason": null, ... } }
  858. # lexical_degrade_reason is "query_fuel_exhausted" when a hybrid search dropped its
  859. # lexical leg because Quill's query fuel ran out (see CASS_QUILL_QUERY_FUEL_BUDGET)
  860. # What the search actually ran (--robot-meta): check this instead of trusting the flags
  861. cass search "error" --robot --robot-meta --days 7 | jq '._meta.effective'
  862. # → { "command": "search", "query": "error",
  863. # "query_structure": "error", // how the engine groups operands: `a OR b c` -> "a OR (b AND c)"
  864. # "query_recoveries": [], // e.g. "1 unclosed '(' closed at the end of the query"
  865. # "db_path": "/home/you/.local/share/coding-agent-search/agent_search.db",
  866. # "db_path_source": "default", // --db | env:CASS_DB_PATH | --data-dir | env:CASS_DATA_DIR | env:XDG_DATA_HOME | default
  867. # "time_window": { "since_ms": 1758067200000, "since_from": "--days 7", "until_ms": null, "until_from": null },
  868. # "filters": { "agents": [], "workspaces": [], "source": "all", "sessions_from_paths": null },
  869. # "auto_corrections": [] } // each argv correction, worded like its stderr note
  870. # `cass pack "error" --json` carries the same object for the search it ran in
  871. # its own `_meta.effective` ("command": "pack", and no search-only "daemon"),
  872. # with home-directory paths, private hosts and secrets redacted like the rest
  873. # of the pack (the db_path above reads "[REDACTED_PATH]/agent_search.db").
  874. # Per-hit trust verdict (advisory; --robot-meta only)
  875. cass search "error" --robot --robot-meta
  876. # Each hit then carries a metadata-only `trust` block:
  877. # "trust": {
  878. # "schema_version": 1,
  879. # "trust_tier": "unverified", // trusted | likely | unverified | stale | failed
  880. # "confidence": "medium", // low | medium | high
  881. # "provenance_refs": [], // e.g. ["commit:ab0d12ef90ab", "bead:xyz", "release:v0.6.15"]
  882. # "stale_reason": "aged_out", // present only when not fully trusted
  883. # "recommended_followup": "..." // advisory next step (never a destructive command)
  884. # }
  885. ```
  886. **How agents should branch on `trust_tier`** (relevance is not correctness — a
  887. hit can be a landed fix or a failed attempt):
  888. | `trust_tier` | Meaning | What to do |
  889. |--------------|---------|------------|
  890. | `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 |
  891. | `likely` | Has provenance (commit/closed bead/release) with `proof_debt` (not claim-proof-pinned) | Confirm via the cited ref first |
  892. | `unverified` | Relevant but no provenance link, or lexical-only corroboration | Corroborate before reuse |
  893. | `stale` | Aged out (`aged_out` in live search; `superseded_by_newer` is schema-defined when supersession markers are supplied) | Prefer a newer result |
  894. | `failed` | A failed/reverted attempt (`failed_attempt`, schema-defined when explicit failure markers are supplied) | Do not reuse |
  895. The verdict is **advisory metadata only** — it never changes result ordering.
  896. It is derived from metadata-only signals (recency, source health, realized
  897. search mode, cwd-relative workspace match, and — opportunistically — linked
  898. commit/bead/release provenance); it carries no raw session text. Live `cass search`
  899. and `cass pack` correlation currently emits `likely`, `unverified`, and `stale`
  900. (with `stale_reason` values `aged_out`, `source_unhealthy`, `workspace_mismatch`,
  901. `proof_debt`, `lexical_only`, or `corroboration_needed`), while `trusted` and
  902. `failed` remain in the schema v1 `TrustTier` vocabulary for explicit proof or
  903. failure inputs. The same `trust` block is attached to `cass pack` evidence.
  904. Branch on `trust_tier` and `stale_reason`, not on `confidence` alone.
  905. Provenance correlation is **project-scoped and explicit-reference anchored**:
  906. for a hit from the project you are running `cass` in now, cass links it to a
  907. closed bead or commit only when the hit's own indexed text references a known
  908. identifier (`bead:<id>` or `commit:<sha>`), joined against that project's local
  909. beads and git history. A linked commit's containing release is resolved from
  910. Git. Release containment preserves provenance but does not establish proof of
  911. the excerpt's claim: a landed commit remains `proof_debt` and cannot become
  912. `trusted` from this correlation alone. A temporal or
  913. workspace coincidence is never enough, so an unrelated conversation never
  914. inherits another's trust. Off-project hits report `workspace_mismatch`, and a
  915. hit whose local source file no longer exists on disk reports `source_unhealthy`
  916. (archive-only) instead of overtrusting a dead path.
  917. ```bash
  918. # Deterministic answer pack for handoff prompts
  919. cass pack "why did checkout fail" --robot --max-tokens 12000 --limit 40
  920. # Freshness-sensitive pack: fail if selected evidence is outside the window
  921. cass pack "checkout timeout after redirect" --robot \
  922. --freshness-policy strict --freshness-window-seconds 604800 \
  923. --max-tokens 12000 --require-evidence
  924. # Token-budgeted pack for pasting into another agent
  925. cass pack "checkout timeout after redirect" --robot \
  926. --max-tokens 4000 --max-evidence 8 --max-sessions 3 --max-excerpt-chars 600
  927. # Pipeline from broad search to a bounded cited handoff
  928. cass search "checkout timeout" --robot-format sessions \
  929. | cass pack "checkout timeout root cause" --robot --sessions-from -
  930. ```
  931. **Design principle**: stdout contains only parseable JSON data; all diagnostics, warnings, and progress go to stderr.
  932. Use `search` when you are still exploring candidate sessions. Use `pack` when
  933. you need a compact, cited, extractive artifact to hand to another agent or a
  934. human operator. Use `status`/`health` before trusting freshness-sensitive output,
  935. and use `doctor` only for diagnostics or safe repair workflows. Use
  936. `export-html` when you need a full browsable session archive; packs are
  937. token-budgeted evidence bundles, not full exports and not external
  938. summarization.
  939. Pack robot output includes `health`, `freshness`, `privacy`, and `warnings`.
  940. Warnings such as `privacy_redactions_applied`, `semantic_fallback_lexical`,
  941. or `no_evidence_found` are data, not prose; branch on the JSON fields before
  942. copying the pack into another tool. Stale selected evidence is structural:
  943. inspect `freshness.stale_evidence_count`.
  944. Packs exclude injected skill payloads by default. Add `--include-skill-content`
  945. to include them explicitly; credential redaction still applies.
  946. `privacy.skill_content_included` reports whether the selected evidence includes
  947. skill payloads, including after token-budget trimming.
  948. ### Swarm Operations Workflow
  949. Use the swarm surfaces when multiple agents are sharing one repo and you need a
  950. single read-only view before claiming work:
  951. ```bash
  952. # Current shared-work snapshot; does not claim, reopen, release, or run builds
  953. cass swarm status --json
  954. # Advisory packet for one bead; still create real reservations and Beads updates yourself
  955. cass swarm work-packet --json --bead coding_agent_session_search-example
  956. # Coordination hygiene check before closeout or takeover review
  957. cass swarm lint --json --bead coding_agent_session_search-example
  958. # Read-only sibling dependency drift sentinel
  959. cass swarm dependency-drift --json
  960. ```
  961. `swarm status`, `swarm work-packet`, `swarm lint`, `swarm evidence`,
  962. `swarm proof-debt` and `swarm failure-patterns` collect the same bounded
  963. read-only Git state and Beads exports when run from the repository root
  964. without a fixture. Git uses
  965. porcelain-v2 with optional locks disabled. Beads uses `br --no-db` (0.6.x or 0.7.x), so its
  966. JSONL snapshot is explicitly partial: unexported database changes may exist.
  967. Recheck Beads and reservations before claiming work. Child commands share a
  968. single 15-second request budget and each has an 8 MiB output cap; Beads categories
  969. cap at 512 issues.
  970. Failures report unavailable providers and unknown summary counts, not zero work.
  971. RCH contributes aggregate active/queued job counts, fleet slots and posture from
  972. `rch status --json` (API 1.0, schema 1.0.0). Responses older than 60 seconds or
  973. more than 5 seconds in the future are unavailable. Worker addresses, commands
  974. and job details are omitted. This provider remains partial: local Cargo/CPU
  975. state and build admission are unknown, even when RCH reports no active jobs.
  976. Agent Mail roster and reservation reads are opt-in: set `CASS_SWARM_AGENT_MAIL_URL`
  977. to the server's HTTP MCP endpoint and, if required, `CASS_SWARM_AGENT_MAIL_TOKEN`.
  978. The reader uses only `resources/read`, never a local database fallback or inbox
  979. read. Mail shares the total request budget with a 3-second cap of its own;
  980. responses are capped at 8 MiB, rosters at 512 agents, and full 250-row reservation
  981. pages are refused. The total reservation count remains unknown; source metadata
  982. reports only the observed active count. Activity and expiry use
  983. the observation time. Task descriptions, reservation reasons and message bodies
  984. are omitted. These observations do not authorize claims or establish proof.
  985. CASS evidence remains unwired. Live lint marks itself partial and adds an
  986. `agent-mail-unavailable` advisory whenever Agent Mail messages are not
  987. collected. Fixture selection (`--fixture <file>` or `--fixture-dir <dir>
  988. --fixture-id <id>`) retains deterministic behavior; `swarm dependency-drift`
  989. also has a live path.
  990. `swarm status` composes Beads, Agent Mail metadata, git state, rch/build
  991. pressure, cass health/status, and proof references. Stale candidates are
  992. advisory only: coordinate through Beads and Agent Mail before reopening,
  993. force-releasing, or taking over work. Suggested commands are robot-safe
  994. templates, not automatic actions.
  995. The TUI's Swarm tab shows the same live payload for the directory the TUI was
  996. started in. Open it from the command palette (`Ctrl+P`, "Swarm operations
  997. cockpit") or by clicking its tab; it has no direct key. Entering the tab
  998. starts one background read with this collector;
  999. until it lands, every count shows as `?`. Counts of providers that could not
  1000. be read stay `?`, never zero. `r` reads again. Rendering never runs a provider
  1001. read.
  1002. `swarm dependency-drift` reads `Cargo.toml` and optional sibling checkouts to
  1003. report manifest pins, local HEAD/dirty state, strict validation commands, and
  1004. release-risk recommendations. It does not fetch remotes, edit manifests, run
  1005. builds, update Beads, send Agent Mail, delete files, or mutate git state.
  1006. When status points at prior evidence, use `cass pack "query" --robot` to create
  1007. a bounded cited handoff for another agent. Packs complement the cockpit; they do
  1008. not replace Beads for ownership, Agent Mail for coordination, or rch for proof
  1009. commands.
  1010. ### Token Budget Management
  1011. LLMs have context limits. `cass` provides multiple levers to control output size:
  1012. | Flag | Effect |
  1013. |------|--------|
  1014. | `--fields minimal` | Only `source_path`, `line_number`, `agent`, `source_id`, `conversation_id` |
  1015. | `--fields summary` | `minimal` plus `title`, `score` |
  1016. | `--fields score,title,snippet` | Custom field selection |
  1017. | `--max-content-length 500` | Truncate long fields (UTF-8 safe, adds "...") |
  1018. | `--max-tokens 2000` | Soft budget (~4 chars/token); adjusts truncation dynamically |
  1019. | `--limit 5` | Cap number of results |
  1020. | `cass pack "query" --robot` | Build a cited handoff pack from selected search evidence |
  1021. | `pack --max-tokens N` | Set the pack planner's soft budget |
  1022. | `pack --max-evidence N` | Cap evidence items selected into the pack |
  1023. | `pack --max-sessions N` | Limit how many sessions can contribute evidence |
  1024. | `pack --max-excerpt-chars N` | Shorten each cited excerpt before token estimation |
  1025. | `pack --fields summary` | Return top-level summary fields for a smaller JSON envelope |
  1026. | `pack --field-mask minimal\|standard\|full` | Select a documented pack projection; `--fields` accepts the same presets |
  1027. | `pack --freshness-policy strict --freshness-window-seconds N` | Reject stale evidence instead of silently mixing it into a pack |
  1028. | `pack --sessions-from FILE` | Restrict pack evidence to newline-delimited session paths; use `-` for stdin |
  1029. Truncated fields include a `*_truncated: true` indicator so agents know when they're seeing partial content.
  1030. Contributor verification for docs or contract changes should use `rch`, for example:
  1031. ```bash
  1032. rch exec -- env CARGO_TARGET_DIR=${TMPDIR:-/tmp}/rch_target_cass_answer_pack_docs \
  1033. cargo test --test golden_robot_docs
  1034. ```
  1035. ### Error Handling for Agents
  1036. Errors are structured, actionable, and include recovery hints. A real sample from `cass search foo --robot` against a fresh data dir:
  1037. ```json
  1038. {
  1039. "error": {
  1040. "code": 3,
  1041. "kind": "missing-index",
  1042. "message": "cass has not been initialized in <data_dir> yet, so search cannot run until the first index completes.",
  1043. "hint": "Run 'cass index --full' once to discover local sessions and build the initial archive.",
  1044. "retryable": true
  1045. }
  1046. }
  1047. ```
  1048. **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.
  1049. **Exit codes** follow a semantic convention:
  1050. | Code | Meaning | Typical action |
  1051. |------|---------|----------------|
  1052. | 0 | Success | Parse stdout |
  1053. | 1 | Health check failed | Run `cass index --full` |
  1054. | 2 | Usage error | Fix syntax (hint provided) |
  1055. | 3 | Index/DB missing | Run `cass index --full` (retryable: true) |
  1056. | 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` |
  1057. | 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 |
  1058. | 6 | Required input missing (password, resume command) | Supply the input (e.g. `--password-stdin`) and rerun |
  1059. | 7 | Lock/busy | Retry later |
  1060. | 8 | Partial result (`sources sync` only: some sources had path failures) | Inspect per-path errors in the JSON output and retry the failed sources |
  1061. | 9 | Unknown error | Check `retryable` flag |
  1062. | 10 | Config / timeout | Depends on `err.kind` |
  1063. | 11 | Config validation | Fix config |
  1064. | 12 | Source / SSH | Check remote host |
  1065. | 13 | Mapping / not-found | Depends on `err.kind` |
  1066. | 14 | I/O / mapping | Retry or inspect path |
  1067. | 15 | Semantic / embedder unavailable | Install model or `--mode lexical` |
  1068. | 20-21 | Model acquisition | Check `err.kind`, `err.hint` |
  1069. | 22 | I/O during model handling | Retry |
  1070. | 23 | Model download | Retry or use `--from-file` |
  1071. | 24 | I/O during model verify/install | Retry |
  1072. | 70 | `cass index` stalled and aborted (kind `index-stalled` envelope on stderr) | Inspect `cass status --json`, then rerun `cass index` |
  1073. | 130 | Interrupted (SIGINT) | Rerun; `cass sources setup --resume` continues an interrupted setup |
  1074. 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`.
  1075. **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.
  1076. 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).
  1077. ### Session Analysis Commands
  1078. Beyond search, `cass` provides commands for deep-diving into specific sessions:
  1079. ```bash
  1080. # Discover the current session for this workspace
  1081. cass sessions --current --json
  1082. # List recent sessions for a specific project
  1083. cass sessions --workspace /path/to/project --json --limit 5
  1084. # Export full conversation to shareable format
  1085. cass export /path/to/session.jsonl --format markdown -o conversation.md
  1086. cass export /path/to/session.jsonl --format json --include-tools
  1087. # Export as self-contained HTML with encryption (recommended for sharing)
  1088. cass export-html /path/to/session.jsonl # To Downloads folder
  1089. printf '%s\n' "pwd" | cass export-html session.jsonl --encrypt --password-stdin
  1090. cass export-html session.jsonl --open --json # Open in browser, JSON output
  1091. # Common agent flow: find current session, then export it
  1092. cass export-html "$(cass sessions --current --json | jq -r '.sessions[0].path')" --json
  1093. # Expand context around a specific line (from search result)
  1094. cass expand /path/to/session.jsonl -n 42 -C 5 --json
  1095. # → Shows 5 messages before and after line 42
  1096. # Activity timeline: when were agents active?
  1097. cass timeline --today --json --group-by hour
  1098. cass timeline --since 7d --agent claude --json
  1099. # → Grouped activity counts, useful for understanding work patterns
  1100. ```
  1101. ### Aggregation & Analytics
  1102. Aggregate search results server-side to get counts and distributions without transferring full result data:
  1103. ```bash
  1104. # Count results by agent
  1105. cass search "error" --robot --aggregate agent
  1106. # → { "aggregations": { "agent": { "buckets": [{"key": "claude_code", "count": 45}, ...] } } }
  1107. # Multi-field aggregation
  1108. cass search "bug" --robot --aggregate agent,workspace,date
  1109. # Combine with filters
  1110. cass search "TODO" --agent claude --robot --aggregate workspace
  1111. ```
  1112. **Aggregation Fields**:
  1113. | Field | Description |
  1114. |-------|-------------|
  1115. | `agent` | Group by agent type (claude_code, codex, cursor, etc.) |
  1116. | `workspace` | Group by workspace/project path |
  1117. | `date` | Group by date (YYYY-MM-DD) |
  1118. | `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 |
  1119. **Response Format**:
  1120. ```json
  1121. {
  1122. "aggregations": {
  1123. "agent": {
  1124. "buckets": [
  1125. {"key": "claude_code", "count": 120},
  1126. {"key": "codex", "count": 85}
  1127. ],
  1128. "other_count": 15
  1129. }
  1130. }
  1131. }
  1132. ```
  1133. Top 10 buckets are returned per field, with `other_count` for remaining items.
  1134. #### Bounded incident mining
  1135. Mine recurrent CASS operational incidents from the canonical archive without
  1136. dumping raw session text:
  1137. ```bash
  1138. cass analytics incidents --limit 10 --json
  1139. # Tighten the bounded scan for automation or a very large archive
  1140. cass analytics incidents --max-sessions 500 --max-messages 50000 \
  1141. --max-bytes 67108864 --budget-ms 5000 --json
  1142. ```
  1143. The response ranks `top_sessions[]` by hit count and category breadth and keeps
  1144. the exact `conversation_id`, agent, host, `source_id`, `source_path`,
  1145. live/archive state, dominant categories, and a structured `cass view` argv.
  1146. That argv carries the effective `--db` path plus `--conversation-id`, so it
  1147. opens the exact ranked archive row even when multiple sessions share a source
  1148. path or the report used a non-default database.
  1149. `total_sessions`, `total_hits`, and `top_sessions_truncated` distinguish the
  1150. bounded ranked result from the totals observed inside the scan scope.
  1151. `discovery.partial` and `stop_reason` explicitly distinguish a bounded partial
  1152. scan from a complete scan. Counts are scoped to scanned candidates whenever the
  1153. scan is partial. `--budget-ms` is a hard wall-clock result guard around the
  1154. independently row-bounded read-only worker. If it expires before a verified
  1155. result arrives, `count_scope="no_verified_results_hard_timeout"` returns an
  1156. empty partial report instead of overstating in-flight observations. Candidate
  1157. discovery is descending archive-row keyset paging;
  1158. `--max-sessions` bounds that newest-row window before dimensional filters, so a
  1159. selective filter can truthfully return a partial empty result instead of scanning
  1160. an unbounded archive. Individual messages are inspected through a bounded 4,096-char
  1161. fragment; an oversized message returns `message-fragment-capped` rather than
  1162. claiming a complete corpus scan. Raw prompt/tool content is always suppressed; evidence carries
  1163. only BLAKE3 fingerprints and basename-redacted paths. The actionable
  1164. `source_path` remains visible solely so the returned view command works.
  1165. ### Chained Search (Pipeline Mode)
  1166. Chain multiple searches together by piping session paths from one search to another:
  1167. ```bash
  1168. # Find sessions mentioning "auth", then search within those for "token"
  1169. cass search "authentication" --robot-format sessions | \
  1170. cass search "refresh token" --sessions-from - --robot
  1171. # Build a filtered corpus from today's work
  1172. cass search --today --robot-format sessions > today_sessions.txt
  1173. cass search "bug fix" --sessions-from today_sessions.txt --robot
  1174. ```
  1175. **How It Works**:
  1176. 1. First search with `--robot-format sessions` outputs one session path per line
  1177. 2. Second search with `--sessions-from <file>` restricts search to those sessions
  1178. 3. Use `-` to read from stdin for true piping
  1179. **Use Cases**:
  1180. - **Drill-down**: Broad search → narrow within results
  1181. - **Cross-reference**: Find sessions with term A, then find term B within them
  1182. - **Corpus building**: Save session lists for repeated searches
  1183. ### Match Highlighting
  1184. 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:
  1185. ```bash
  1186. cass search "authentication error" --robot --highlight
  1187. # "snippet": "... **authentication** failed with **error** ..."
  1188. ```
  1189. Highlighting is query-aware: quoted phrases like `"auth error"` highlight as a unit; individual terms highlight separately.
  1190. ### Pagination & Cursors
  1191. For large result sets, use cursor-based pagination:
  1192. ```bash
  1193. # First page
  1194. cass search "TODO" --robot --robot-meta --limit 20
  1195. # → { "hits": [...], "_meta": { "next_cursor": "eyJ..." } }
  1196. # Next page
  1197. cass search "TODO" --robot --robot-meta --limit 20 --cursor "eyJ..."
  1198. ```
  1199. 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.
  1200. ### Match Counts: Exact or Lower Bound
  1201. `total_matches` answers "how many messages match?", but it is exact only when
  1202. cass can afford to count. Every search fetches one hit beyond `--limit` to learn
  1203. whether another page exists. When the page is full and the index is larger than
  1204. `CASS_SEARCH_EXACT_TOTAL_COUNT_MAX_DOCS` documents, cass skips the full count
  1205. and reports that `limit + 1` as a lower bound. Below the threshold it counts
  1206. every match.
  1207. | Build | Threshold | `stale lock` with `--limit 10` on a 1,034,219-document index |
  1208. |-------|-----------|---------------------------------------------------------------|
  1209. | v0.9.0 and earlier | 50,000 documents | `total_matches: 11` |
  1210. | v0.10.0 and later | 5,000,000 documents | `total_matches: 11915` |
  1211. `--robot-meta` says which kind of number you got:
  1212. ```bash
  1213. cass search "stale lock" --robot --robot-meta --limit 10 \
  1214. | jq '{total_matches, precision: ._meta.cursor_manifest.count_precision, why: ._meta.cursor_manifest.count_reason}'
  1215. # → {"total_matches": 11915, "precision": "exact", "why": "total_matches is exact; no extra recount was needed"}
  1216. # A lower bound reads "precision": "lower_bound".
  1217. ```
  1218. **Why the threshold moved.** The 50,000 cap dates from the Tantivy engine,
  1219. where counting a common term over millions of documents could dominate the
  1220. query. The Quill engine counts cheaply. Paired runs on that 1,034,219-document
  1221. archive, capped against exact (`--limit 10`, read-only, CPU time):
  1222. | Query | Exact total | Extra CPU for the exact count |
  1223. |-------|-------------|-------------------------------|
  1224. | `stale lock` | 11,915 | ~0.00-0.04 s |
  1225. | `cargo build` | 24,944 | ~0.01-0.03 s |
  1226. | `the` | 439,461 | ~0.03-0.05 s |
  1227. | `AGENTS.md` | 867,087 | ~0.06-0.11 s |
  1228. Each search cost about 0.8 s of CPU either way. The capped answer, meanwhile,
  1229. was wrong by up to five orders of magnitude, and agents read `total_matches` as
  1230. a count. The default now covers five times that archive; set
  1231. `CASS_SEARCH_EXACT_TOTAL_COUNT_MAX_DOCS=0` to never count exactly, or raise it
  1232. for a larger archive.
  1233. **Aggregations have their own window.** `--aggregate` buckets are computed over
  1234. the top `max(1000, limit + offset)` hits, so bucket counts on a large archive
  1235. describe the best-ranked thousand matches, not the whole corpus. Use an exact
  1236. `total_matches` for "how many", and aggregations for "how are the top hits
  1237. distributed".
  1238. ### Request Correlation
  1239. For debugging and logging, attach a request ID:
  1240. ```bash
  1241. cass search "bug" --robot --request-id "req-12345"
  1242. # → { "request_id": "req-12345", "hits": [...], ... }
  1243. # (top level always; also under _meta.request_id with --robot-meta)
  1244. ```
  1245. ### Idempotent Operations
  1246. For safe retries (e.g., in CI pipelines or flaky networks):
  1247. ```bash
  1248. cass index --full --idempotency-key "build-$(date +%Y%m%d)"
  1249. # If same key + params were used in last 24h, returns cached result
  1250. ```
  1251. ### Query Analysis
  1252. Debug why a search returned unexpected results:
  1253. ```bash
  1254. cass search "auth*" --robot --explain
  1255. # → Adds "explanation": the sanitized query, flat lists of its terms, phrases and
  1256. # operators (not a tree), the query type and index strategy, a low/medium/high cost
  1257. # class, a filter summary and warnings. Wildcards are reported, not expanded.
  1258. cass search "auth error" --robot --dry-run
  1259. # → Validates query syntax without executing
  1260. ```
  1261. ### Traceability
  1262. For debugging agent pipelines:
  1263. ```bash
  1264. cass search "error" --robot --trace-file /tmp/cass-trace.json
  1265. # Appends execution span with timing, exit code, and command details
  1266. cass index --full --json --robot-trace-ingest 2>/tmp/cass-ingest-trace.jsonl
  1267. # Streams one NDJSON record per ingest batch with wall_ms, batch_msgs,
  1268. # inserted_messages, and duplicate-lookup counters for perf bisects
  1269. ```
  1270. ### Search Flags Reference
  1271. | Flag | Purpose |
  1272. |------|---------|
  1273. | `--robot` / `--json` | JSON output (pretty-printed) |
  1274. | `--robot-format jsonl\|compact` | Streaming or single-line JSON |
  1275. | `--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) |
  1276. | `--fields minimal\|summary\|<list>` | Reduce payload size |
  1277. | `--max-content-length N` | Truncate content fields to N chars |
  1278. | `--max-tokens N` | Apply an approximate token budget to robot output |
  1279. | `--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` |
  1280. | `--cursor <token>` | Cursor-based pagination (from `_meta.next_cursor`) |
  1281. | `--request-id ID` | Echoed in response for correlation |
  1282. | `--aggregate agent,workspace,date` | Server-side aggregations |
  1283. | `--explain` | Include query analysis (parsed query, cost estimate) |
  1284. | `--dry-run` | Validate query without executing |
  1285. | `--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`) |
  1286. | `--source <source>` | Filter by source: `local`, `remote`, `all`, or specific source ID |
  1287. | `--highlight` | Also mark query-term occurrences the engine left unmarked (snippets always mark matched terms with `**`) |
  1288. ### Index Flags Reference
  1289. | Flag | Purpose |
  1290. |------|---------|
  1291. | `--idempotency-key KEY` | Safe retries: same key + params returns cached result (24h TTL) |
  1292. | `--json` | JSON output with stats |
  1293. | `--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) |
  1294. | `--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) |
  1295. When `health --json` or `status --json` reports `index.status: "hollow"`, the
  1296. live Quill generation serves fewer than half the documents certified by its
  1297. completed rebuild checkpoint. `index.live_documents` reports the served count.
  1298. Run `cass index` to let its pre-scan repair rebuild from the canonical archive;
  1299. `cass index --full` also rescans the session sources. A missing count provides
  1300. no hollow-generation verdict.
  1301. `index.manifest_source` (also under search `--robot-meta`
  1302. `_meta.index_freshness` and in `cass serve`'s `snapshot`) names the MANIFEST
  1303. slot readers serve: `current`,
  1304. `previous_after_missing_current` or `previous_after_corrupt_current`. A corrupt
  1305. current MANIFEST is read through `MANIFEST.prev`, the generation before the
  1306. newest publish, so the index reports `stale` and `health` reports it as an
  1307. error; `cass index` rebuilds the generation from the canonical archive.
  1308. ### Recovering an Interrupted Lexical Rebuild
  1309. Rerun `cass index --full --rebuild-profile bounded --json` after an interrupted
  1310. rebuild. A saved scratch generation can retain its committed documents when
  1311. new conversations or messages have entered the canonical archive, including
  1312. messages appended to conversations it already processed. Recovery streams the
  1313. canonical archive again to verify those documents and adds only missing
  1314. document identities. Final segment maintenance can still rewrite retained
  1315. segments. Verification progress therefore starts at the first conversation;
  1316. that does not mean the committed index work was discarded.
  1317. Every retained document must match the canonical identity and full projected
  1318. content, and every document in the saved generation must be accounted for.
  1319. Edits or deletions affecting retained search documents, a replaced archive,
  1320. incompatible projection settings, and damaged or inconsistent index evidence
  1321. reject reuse. The rejected candidate is retained in a
  1322. `.lexical-rebuild-quarantine-*` directory and a fresh replacement is built
  1323. off-live. Explicit `--force-rebuild` still requests a fresh pass: it never
  1324. reuses a generation from before it started. If that pass is itself
  1325. interrupted, rerunning `cass index --force-rebuild` with the same cass build
  1326. continues it, provided the archive has not been written since the pass began.
  1327. The rerun reads the archive from the start again but indexes only the
  1328. conversations the pass had not committed, or only finishes its final merge.
  1329. Any archive write, another cass build, or `--full` starts over.
  1330. The audit shares the immutable native snapshot admitted by the candidate's
  1331. writer. It does not independently open an earlier generation and then assume
  1332. the writer received the same one. Publication retains the fingerprint of the
  1333. generation verified while that writer was held; a later native generation
  1334. change returns a retryable failure without transferring the old content proof.
  1335. Recovery checkpoints bind the archive's stable file identity, lexical schema,
  1336. packet contract, and per-message content cap. Older version-three checkpoints
  1337. that explicitly identify a staged single index can be adopted only through
  1338. the complete content audit; their old conversation cursor never authorizes
  1339. skipping rows. They cannot establish historical file identity before that
  1340. upgrade. Incomplete shared-writer and live-index checkpoints restart off-live,
  1341. including checkpoints that carry an archive binding.
  1342. Completed generations are also bound to their native manifest and the observed
  1343. canonical DB/WAL write epoch. If that evidence has changed, an explicit rebuild
  1344. performs a bounded read-only content audit before reusing the live generation.
  1345. This includes harmless bookkeeping writes: equal row counts alone never renew
  1346. rebuild authority. A matching audit retains the index without rewriting its
  1347. documents; a mismatch starts a replacement off-live. Successful verification
  1348. refreshes the paired generation and equivalence evidence before recording
  1349. completion, while leaving the native index unchanged.
  1350. Search and status distinguish a verified current generation from an
  1351. `unverified` one. Bookkeeping or WAL changes can make source evidence
  1352. unverified while the complete native generation remains readable. Reads keep
  1353. serving that generation with the verification reason; the label alone does
  1354. not start a full content audit or a rebuild loop. Ordinary count drift,
  1355. pending replay work, and source-scan scheduling keep their existing refresh
  1356. behavior. A confirmed archive-identity or projection-contract mismatch
  1357. requires repair. The archive-fingerprint cache cannot renew an older
  1358. checkpoint's authority under a newer database identity.
  1359. Newly indexed batches are committed and checkpointed durably. A further
  1360. interruption preserves those batches too. Readers keep the prior published
  1361. generation until the candidate, its manifest, and its completed receipt are
  1362. ready for the existing atomic swap. A canonical database write detected during
  1363. verification or publication returns an error and retains the generation for a
  1364. verified retry. Any saved completion evidence remains bound to the source
  1365. epoch that was actually audited. CASS's archive writer lease excludes
  1366. cooperating canonical writers; external session files can keep growing, and a
  1367. later indexing scan ingests those files after canonical recovery finishes.
  1368. The bounded profile, per-message cap, responsiveness limits, disk headroom
  1369. checks, and bounded merge planner still apply. The audit does not retain an
  1370. archive-sized set of message identities. Its source reads and native content
  1371. checks still cost time, and the existing controls do not guarantee a fixed
  1372. total-process RSS ceiling. See [the recovery design and validation
  1373. record](docs/perf/issue-496-lexical-resume.md) for the test matrix and measured
  1374. scope.
  1375. ### Robot Documentation System
  1376. For machine-readable documentation, use `cass robot-docs <topic>`:
  1377. | Topic | Content |
  1378. |-------|---------|
  1379. | `commands` | Full command reference with all flags |
  1380. | `env` | Environment variables and defaults |
  1381. | `paths` | Data directory locations per platform |
  1382. | `guide` | Quick start guide for automation |
  1383. | `schemas` | JSON response schemas |
  1384. | `exit-codes` | Exit code meanings and retry guidance |
  1385. | `examples` | Copy-paste usage examples |
  1386. | `contracts` | API contract version and stability |
  1387. | `sources` | Remote sources configuration guide |
  1388. ```bash
  1389. # Get documentation programmatically
  1390. cass robot-docs guide
  1391. cass robot-docs schemas
  1392. cass robot-docs exit-codes
  1393. # Machine-first help (wide output, no TUI assumptions)
  1394. cass --robot-help
  1395. ```
  1396. ### API Contract & Versioning
  1397. `cass` maintains a stable API contract for automation:
  1398. ```bash
  1399. cass api-version --json
  1400. # → { "crate_version": "<cargo version>", "build_commit": "<sha or unknown>", "api_version": 1, "contract_version": "1" }
  1401. cass introspect --json
  1402. # → Full schema: all commands, arguments, response types
  1403. ```
  1404. **Contract Version**: Currently `1`. Increments only on breaking changes.
  1405. **Guaranteed Stable**:
  1406. - Exit codes and their meanings
  1407. - JSON response structure for `--robot` output
  1408. - Flag names and behaviors
  1409. - `_meta` block format
  1410. ### Ready-to-paste blurb for AGENTS.md / CLAUDE.md
  1411. ```
  1412. 🔎 cass — Search All Your Agent History
  1413. 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.
  1414. ⚠️ NEVER run bare cass — it launches an interactive TUI. Always use --robot or --json.
  1415. Quick Start
  1416. # One-shot agent triage (read next_command when present)
  1417. cass triage --json
  1418. # Search across all agent histories
  1419. cass search "authentication error" --robot --limit 5
  1420. # Build a cited handoff pack from search evidence
  1421. cass pack "authentication error root cause" --robot --max-tokens 12000 --limit 40
  1422. # Tight handoff budget with freshness and privacy metadata
  1423. cass pack "authentication error root cause" --robot --max-tokens 4000 --max-evidence 8 --fields summary
  1424. # View a specific result (from search output)
  1425. cass view /path/to/session.jsonl -n 42 --json
  1426. # Expand context around a line
  1427. cass expand /path/to/session.jsonl -n 42 -C 3 --json
  1428. # Learn the full API
  1429. cass capabilities --json # Static agent self-description
  1430. cass robot-docs guide # LLM-optimized docs
  1431. Why Use It
  1432. - Cross-agent knowledge: Find solutions from Codex when using Claude, or vice versa
  1433. - Forgiving syntax: Typos and wrong flags are auto-corrected with teaching notes
  1434. - Token-efficient: --fields minimal returns only essential data; pack budgets cite only selected evidence
  1435. - Copy-safe handoffs: pack warnings include freshness and privacy/redaction status
  1436. Key Flags
  1437. | Flag | Purpose |
  1438. |------------------|--------------------------------------------------------|
  1439. | --robot / --json | Machine-readable JSON output (required!) |
  1440. | --fields minimal | Reduce payload: source_path, line_number, agent, source_id, conversation_id |
  1441. | pack --max-tokens N | Budget a cited handoff pack |
  1442. | --limit N | Cap result count |
  1443. | --agent NAME | Filter to specific agent (claude, codex, cursor, etc.) |
  1444. | --days N | Limit to recent N days |
  1445. stdout = data only, stderr = diagnostics. Exit 0 = success.
  1446. ```
  1447. ---
  1448. ## 🔤 Query Language Reference
  1449. `cass` supports a rich query syntax designed for both humans and machines.
  1450. ### Basic Queries
  1451. | Query | Matches |
  1452. |-------|---------|
  1453. | `error` | Messages containing "error" (case-insensitive) |
  1454. | `python error` | Messages containing both "python" AND "error" |
  1455. | `"authentication failed"` | Exact phrase match |
  1456. | `auth fail` | Both terms, in any order |
  1457. ### Boolean Operators
  1458. Combine terms with explicit operators for complex queries:
  1459. | Operator | Example | Meaning |
  1460. |----------|---------|---------|
  1461. | `AND` | `python AND error` | Both terms required (default) |
  1462. | `OR` | `error OR warning` | Either term matches |
  1463. | `NOT` | `error NOT test` | First term, excluding second |
  1464. | `-` | `error -test` | Shorthand for NOT |
  1465. **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.
  1466. **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.
  1467. ```bash
  1468. # Complex boolean query
  1469. cass search "authentication AND (error OR failure) NOT test" --robot
  1470. # Exclude test files
  1471. cass search "bug fix -test -spec" --robot
  1472. # Either error type
  1473. cass search "TypeError OR ValueError" --robot
  1474. ```
  1475. ### Phrase Queries
  1476. Wrap terms in double quotes for exact phrase matching:
  1477. | Query | Matches |
  1478. |-------|---------|
  1479. | `"file not found"` | Exact sequence "file not found" |
  1480. | `"cannot read property"` | Exact JavaScript error message |
  1481. | `"def test_"` | Function definitions starting with test_ |
  1482. Phrases match their words adjacent and in order (no slop). Useful for error messages, code patterns, and specific terminology.
  1483. ### Wildcard Patterns
  1484. | Pattern | Type | Matches | Performance |
  1485. |---------|------|---------|-------------|
  1486. | `auth*` | Prefix | "auth", "authentication", "authorize" | Fast (uses edge n-grams) |
  1487. | `*tion` | Suffix | "authentication", "function", "exception" | Slower (term-dictionary expansion) |
  1488. | `*config*` | Substring | "reconfigure", "config.json", "misconfigured" | Slowest (term-dictionary expansion) |
  1489. | `test_*` | Prefix on `test` | anything whose token starts with "test" | Fast |
  1490. **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).
  1491. Accented Latin queries use the same fragments as the existing index. For example,
  1492. `"kérlek"` requires adjacent exact `k` and `rlek` terms in one field. Bare words
  1493. of 2–20 Unicode scalars retain the existing implicit final-token prefix:
  1494. `kérlek` also matches `kérleknek`, while `"kérlek"` does not. An explicit
  1495. `kérl*` requires `k` followed by a term starting with `rl`. These prefixes search the full
  1496. dictionary, including text beyond the first 4 KiB and prefixes longer than 20
  1497. characters. They allow up to 1,024 matching terms per field and immutable index
  1498. segment; exceeding that budget returns an error instead of a partial result.
  1499. If a final accented character was discarded by the original tokenizer, the last
  1500. surviving fragment stays exact: `café*` searches for `caf`, not `cafeteria`.
  1501. This correction reads the existing `v9-quill` index without a schema rebuild.
  1502. The existing ingestion fingerprint policy may revalidate source files on the
  1503. next incremental indexing run after the dependency update.
  1504. It preserves the old tokenizer's limits: adjacent literal `k rlek` can match
  1505. `kérlek`, and canonically equivalent Unicode spellings can produce different
  1506. terms. Mixed CJK queries require the analyzer's actual terms in one field, with
  1507. the existing conjunction behavior for overlapping bigrams. Unsupported scripts
  1508. or an operand with no indexed terms refuse the whole nonempty query, including
  1509. under `OR` and `NOT`; they cannot turn into an empty browse query. Accented
  1510. suffix, substring and interior wildcard patterns are unsupported. A quoted
  1511. phrase ignores edge stars under the existing syntax but rejects interior stars.
  1512. ### Query Modifiers
  1513. ```bash
  1514. # Field-specific search (in robot mode)
  1515. cass search "error" --agent claude --workspace /path/to/project
  1516. # Time-bounded search
  1517. cass search "bug" --since 2024-01-01 --until 2024-01-31
  1518. cass search "bug" --today
  1519. cass search "bug" --days 7
  1520. # Combined filters
  1521. cass search "authentication" --agent codex --workspace myproject --week
  1522. ```
  1523. ### Flexible Time Input
  1524. `cass` accepts a wide variety of time/date formats for filtering:
  1525. | Format | Examples | Description |
  1526. |--------|----------|-------------|
  1527. | **Relative** | `-7d`, `-24h`, `-30m`, `-1w` | Days, hours, minutes, weeks ago |
  1528. | **Keywords** | `now`, `today`, `yesterday` | Named reference points |
  1529. | **ISO 8601** | `2024-11-25`, `2024-11-25T14:30:00Z` | Standard datetime |
  1530. | **US Dates** | `11/25/2024`, `11-25-2024` | Month/Day/Year |
  1531. | **Unix Timestamp** | `1732579200`, `-1` | Seconds since epoch (negative before 1970) |
  1532. | **Unix Millis** | `1732579200000`, `-315619200000` | Milliseconds (auto-detected) |
  1533. **Intelligent Heuristics**:
  1534. - Numbers whose absolute value is 100,000,000,000 (10^11) or more are milliseconds; smaller magnitudes are seconds
  1535. - Years are written in full (`2024`, not `24`)
  1536. - 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
  1537. - 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
  1538. ```bash
  1539. # All equivalent for "last week"
  1540. cass search "bug" --since -7d
  1541. cass search "bug" --since "-1w"
  1542. cass search "bug" --days 7
  1543. # Date range
  1544. cass search "feature" --since 2024-01-01 --until 2024-01-31
  1545. # Mix formats
  1546. cass search "error" --since yesterday --until now
  1547. ```
  1548. ### Match Types
  1549. 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).
  1550. | Type | Meaning | Match Quality order |
  1551. |------|---------|---------------------|
  1552. | `exact` | No wildcards: exact terms (and edge n-gram prefixes) | 1 |
  1553. | `prefix` | Trailing wildcard (`auth*`) | 2 |
  1554. | `suffix` | Leading wildcard (`*tion`) | 3 |
  1555. | `substring` | Both sides (`*config*`) | 4 |
  1556. | `wildcard` | Inner wildcard (`f*o`) | 5 |
  1557. | `implicit_wildcard` | Automatic wildcard fallback on a sparse exact search | 6 |
  1558. Relevance scores carry no boost for the match type; only the TUI's Match Quality ranking mode (`F12`) orders by it.
  1559. ### Auto-Fuzzy Fallback
  1560. When an exact query's first page returns fewer than 3 results (or fewer than a smaller `--limit`), `cass` retries with wildcard expansion:
  1561. - `auth` → `*auth*`
  1562. - 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.
  1563. - It skips queries that already use wildcards, boolean operators or phrases, and zero-hit queries containing a token longer than 16 characters.
  1564. - 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`
  1565. - TUI shows a "fuzzy" indicator in the status bar
  1566. ---
  1567. ## ⌨️ Complete Keyboard Reference
  1568. ### Global Keys
  1569. | Key | Action |
  1570. |-----|--------|
  1571. | `Ctrl+C` | Force quit |
  1572. | `Esc` / `F10` | Unwind: close the open modal or surface, otherwise quit |
  1573. | `F1` / `Alt+?` | Toggle help screen |
  1574. | `F2` / `Alt+T` | Next theme (cycles all 19 presets) |
  1575. | `Shift+F2` / `Alt+Shift+T` | Previous theme |
  1576. | `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 in

Free to use. If it’s helped, pass it on.