Repository navigation
Architecture
Current as of v1.3.2. How Longhand turns a directory of JSONL files into sub-second semantic recall over your entire Claude Code (and Codex) history.
JSONL files (~/.claude/projects/, ~/.codex/sessions + archived_sessions)
↓
Parser (longhand/parser.py) + Codex adapter (longhand/codex.py)
↓
Storage: events (+ vectors), tool pairs, git operations — SQLite + ChromaDB
↓
Analysis (project inference, outcome classification, episode/segment extraction + embedding)
↓
Recall layer (time parsing, project matching, episode ranking, narrative)
↓
CLI + two MCP servers
Events, their vectors, tool pairs, and git operations are stored before analysis runs — analysis is a distinct, re-runnable pass over data that's already durable, not a gate on ingest.
-
SessionEnd hook → hidden
ingest-session. Reads bounded stdin JSON (≤256KB) and runs a full ingest plus analysis for the session that just closed. Hook mode always exits 0 — failures are logged tologs/hook-errors-YYYY-MM-DD.log, never raised to Claude Code. If another ingest holds the lock it doesn't wait: since 1.3.1 it hands the session to a background retry (see Concurrency, below). -
Stop hook → hidden
ingest-live, fired once per assistant turn. Reads new complete lines from the transcript's last known offset and writes events, tool pairs, and the session row — no embeddings, no analysis. This is what makes an in-progress session queryable, butrecall/semanticsearchdon't see it until SessionEnd runs the full pipeline. A turn that finds the lock busy goes to the same kind of background retry instead of waiting for the next Stop, which never comes if the session ends on that turn. -
UserPromptSubmit hook →
__prompt-hook-run→ the hiddencontextcommand → the recall pipeline →additionalContext. Gated byhook.min_relevanceand capped byhook.max_inject_chars(see Configuration); the injected text includes the age-gap "Note: …" when that applies (see Recall pipeline, below). -
Manual commands:
longhand ingest(skips already-indexed files by size unless--force) andlonghand setup(always re-ingests everything). -
Reconciler:
longhand reconcile [--fix]sorts on-disk transcripts into missing, null-project, partially-indexed (stagepending— a crash mid-pipeline), changed, and oversize buckets, and handles the Codex side too. Changed (1.3.1+) means the transcript grew after its last full ingest and has been quiet for 30 minutes — a turn its own hooks never captured — and--fixre-ingests it; one that grew but was written more recently is only counted, as settling, and left to its session's hooks. The Stop hook's live tail doesn't count as a full ingest here, because it never embeds or analyzes. The macOS-only launchd jobcom.longhand.reconcile(longhand schedule install-reconciler) runsreconcile --fixevery 30 minutes and bakes the resolvedLONGHAND_DATA_DIRinto its plist, since launchd doesn't read your shell profile. -
Self-heal during recall: a cheap project-inference pass, plus a detached
python -m longhand ingestspawned in the background when no project matches at all; a backgroundbackfill-episodesrun when the episode vector collection is empty but SQLite already has episode rows. -
Codex capture runs in two passes via
codex-sync(see below). -
Concurrency: a PID lockfile (
.ingest.lock, mode 0600). Hooks never wait for it. Since 1.3.1, a Stop or SessionEnd hook that finds it busy starts a detached retry instead —ingest-liveoringest-session --transcript <path> --wait-lock 600— one per transcript and hook (a PID marker underlive-retry/orsession-retry/in the data directory), which waits up to 10 minutes for the lock and then reads the transcript to its end. Each retry logs tologs/live-retry-YYYY-MM-DD.logorlogs/session-retry-YYYY-MM-DD.log; one that gives up leaves alock-timeoutbreadcrumb inlogs/hook-errors-YYYY-MM-DD.log(retry-spawn-failedif it couldn't start), anddoctorcounts both as healable byreconcile --fix. CLI commands differ by how much a lock conflict matters to them:analyze,reattribute --fix, andredact --applywait up to 15 seconds for the holder to finish;ingestskips immediately with a message;reconcile --fixanddb vacuumexit 1;codex-syncreports"locked": truein its JSON output and moves on;setupjust defers whichever individual session's ingest lost the race, without failing the run. SQLite itself runs in WAL mode with a 30-second busy timeout.
codex-sync discovers rollouts under CODEX_HOME (default ~/.codex), scanning both its sessions and archived_sessions subdirectories, and skips threads Codex spawned for itself (like its approval-reviewer subagent) unless --include-subagents.
-
Pass 1 (always): every new or changed rollout is captured exact-record-only — stage
archived, no Chroma, no embedding model loaded. Every message, reasoning summary, tool call, and output is stored verbatim and keyword-searchable via the shared server. -
Pass 2, the finalizer: any rollout quiet for
--finalize-afterseconds (default 1800 = 30 min) gets the full pipeline — embeddings, episodes, project inference — one thread per run, so a 60-second poller stays bounded.--semanticruns the full pipeline on everything immediately;--no-finalizekeeps a run exact-only.reconcile --fixruns both passes.
Running analyze on an archived Codex session is actively harmful, not just useless: it stamps that session analyzed without ever embedding it, which makes the finalizer skip it from then on (#97). Use codex-sync --semantic for Codex threads instead.
longhand/parser.py enforces hard bounds — 500MB per session file, 50MB per JSONL line — and produces one Event per content block, with duplicate IDs disambiguated by a #n suffix.
-
Skipped by design (never stored, not even as unknown):
queue-operation,progress,last-prompt,mode,permission-mode,attachment,ai-title,agent-name,file-history-delta, and (since 1.3.2) Claude Code 2.1's request telemetry:api-request,api-request-blob,api-request-shape,atis-latch,tools-used. -
Preserved as known unknowns (stored, not surfaced as drift):
summary,pr-link,worktree-state,frame-link, and (since 1.3.2)custom-title,agent-setting,relocated,cost-state. - Error detection and git-operation extraction both work at per-event granularity — the former during parsing itself, the latter as a pass over the parsed event list before analysis runs.
- The project directory is inferred as the most common working directory across the session's events that resolves to an actual project root, ignoring
$HOME. Discovery skips anything under asubagents/directory and pytest temp-directory leftovers — so a subagent's own transcript file is never discovered as a separate session in its own right.
Codex mode switches on when the first session_meta record appears in a rollout. Messages, reasoning (when Codex provides a readable summary — encrypted reasoning has none and is skipped), and tool calls/outputs become events. Codex writes every message twice — once as a canonical response_item, once as a UI event_msg mirror — and the mirrors are skipped, along with non-content bookkeeping: the top-level token_usage_record, world_state, and (since 1.2.2) compacted records, and turn-bookkeeping event_msg kinds such as task_started, task_complete, item_completed, token_count, and thread_settings_applied. Event IDs are namespaced codex:<id>; cmd: literals inside exec scripts are decoded so shell commands still feed error detection and git extraction.
Data-dir resolution: an explicit flag, then LONGHAND_DATA_DIR, then ~/.longhand — meant to be created mode=0o700, but at least four other code paths (the update-check cache, config --set, schedule install-reconciler, and the hook-error logger) can create it first at the default umask instead, and a later mkdir(mode=0o700, exist_ok=True) never retroactively tightens a directory that already exists (#99; see Configuration).
SQLite tables: sessions, events (including a raw_json column — nothing lossy about the verbatim record), ingestion_log (file_size, last_offset, and an analysis_stage column of NULL/pending/events/analyzed/archived), projects, session_outcomes, episodes (including fix_commit_hash), tool_pairs, git_operations, conversation_segments, schema_version, and a plans_index view over Write/Edit events touching ~/.claude/plans/*.md. Migrations run automatically and are numbered (currently 8); a database stamped with a migration this build doesn't know about is refused loudly (SchemaTooNewError) rather than opened blind.
ChromaDB: 5 collections — events, sessions, projects, segments, episodes — sharing one CPU-only ONNX all-MiniLM-L6-v2 embedding model (no GPU, not configurable, not reloaded per collection). Documents are truncated to 2,000 characters before embedding; upserts batch 500 at a time.
Ingest order (per session): mark analysis_stage = 'pending', write the session row + events, embed the events, link tool pairs, extract + store git operations, write the ingestion_log entry, then run analysis (or stamp analysis_stage = 'events' and stop there if --skip-analysis was passed).
analyze_session first deletes the session's existing episodes and segments (safe to re-run; boundaries can shift when extractors change), then:
- Infers the project, attaches the session to it, and embeds a project summary.
- Classifies the session's outcome (shipped, fixed, stuck, abandoned, or exploratory).
- Extracts problem→fix episodes and embeds only the ones with an identified fix (fixless episodes — e.g. a "command not found" that never led to an edit — stay in SQLite for forensic lookup but don't clutter vector search with thin snippets).
- Extracts conversation segments (
debugging,design,planning,story, ordiscussion) and embeds all of them. - Embeds a whole-session summary.
- Stamps the ingestion stage
analyzed.
longhand analyze (with or without --all) re-runs this over already-ingested sessions but never re-embeds the events themselves — it runs analyze_session directly on stored rows and never goes through ingest_session, the step that embeds events. Event vectors are written whenever a session goes through ingest_session: ingest, setup, and the SessionEnd hook do that for every session they ingest, ingest --force for already-indexed ones, and reconcile --fix, restore, codex-sync --semantic, and the finalizer only for the sessions they pick up. With --all specifically, analyze additionally clears and rebuilds the episode vector collection from current SQLite rows, since a boundary-drawing change can otherwise leave stale embeddings under old episode IDs — and the rebuilt collection uses the same CPU-pinned ONNX embedder as every other collection (since 1.3.2; before that it silently fell back to Chroma's default embedding function, #98). longhand reattribute re-derives just the project-ownership piece, independently, from the events table (so it still works on sessions whose transcript file has rotated off disk).
- Kick off a background episode-vector backfill if the collection is empty but SQLite has rows.
- Parse any time phrase in the query, anchored to the local calendar day.
- Match candidate projects (by alias, category, meaning, and recency), plus any projects turned up by searching session summaries.
- Search episodes by meaning within those filters, relaxing them if nothing comes back — first dropping the project filter, then the fix requirement.
- Rank candidates: semantic similarity ×20, +10 per keyword hit, plus confidence, plus up to 0.5 for recency (recency is a tiebreaker, not a driver — an old episode can still outrank a fresh one on the same topic).
- Apply a quality gate: vector distance under 1.5, or a combined score of 15+.
- Always search conversation segments in parallel; fall back to raw events only if episodes fail the quality gate.
- Pick a primary result — episodes first, then segments, then the event fallback — with any leftover segments folded into a footer.
- Load reconstructed-file-state artifacts for the top episode.
- Age-gap note (1.2.2): when the query had no time phrase and the top episode is both ≥30 days old and ≥30 days older than the newest of the other returned episodes (whichever runner-up has the most recent date, not necessarily rank #2), attach a note calling that out — ranking itself is never changed by this, it only adds information.
- Build the markdown narrative.
recall_project_status and its staleness detection (the stale/stale_reason fields other tools also surface) are a related but separate code path from the general-query pipeline above.
-
Semantic
longhand— 13 tools listed, 19 names still answered (6 retired names keep working forever with a[DEPRECATED]preamble). One store instance for the whole process lifetime, so the Chroma index loads once. Every tool exceptreconcilecarries a read-only annotation; errors come back as a JSON envelope rather than a raw traceback. Started by the hiddenmcp-servercommand (via the plugin's.mcp.json, orclaude mcp add),mcp serve, orpython -m longhand.mcp_server. -
Shared
longhand-shared— a FastMCP server exposing 4 read-only SQL tools over a read-only database connection:list_sessions,search(literal phrase, exactsession_id),get_session_timeline,get_event_text. RespectsLONGHAND_DATA_DIR, runs every query against a fixed per-query work budget, and never touches Chroma or loads a model. Started withshared-mcp, for Codex and Claude Code alike.
The database file itself cannot go to a git host (GitHub blocks files over 100 MiB and pushes over 2 GB), so the backup is an export of the verbatim record, and restore is the existing ingest path. Everything lives under longhand/backup/:
-
export.py— one session at a time, streamed fromevents.raw_jsonin event order, one line per distinct stored line, everyredactpattern masked in the copy (private-key blocks whole), split into 40 MB parts, with asession.jsoncarrying the row, the part list, the line count, and the sha256 of the transcript. -
state.py— the localbackup-state.json: per-session marks (event count, last event timestamp, ingested-at, sha256) that make "what changed?" oneGROUP BYquery, never uploaded. -
merge.py— the never-shrink rule: a staged export that matches the repository's sha is dropped, one whose lines are a subset leaves the repository untouched, otherwise the union is written (repository order first, local-only lines appended). Every change to a live session directory is a sidecar swap (<dir>.merge→ rename → remove<dir>.old), andrecover_interruptedfinishes or undoes whatever a killed run left. -
gitrepo.py— the argv-only git wrapper (git -c protocol.ext.allow=never -C <clone> …—cloneandls-remotewithout-C— with--before remotes and paths git takes positionally), remote validation, and the GitHub visibility check throughgh. -
service.py— a run: takebackup.lock, recover, commit any leftover, fetch and fast-forward (a diverged clone is reset to the remote; nothing is ever rebased), export the changed sessions, commit in batches of about 500 MB (the manifest is written into each commit), push, and save the state file. Auto mode is the same function called fromreconcile --fixat most hourly. -
restore.py— read everysession.json, verify the sha256 and the line sizes, re-parse Claude transcripts throughJSONLParserand Codex rollouts throughCodexAdapter, andingest_sessionthem under the ingest lock; seed the state file so a restored machine that keeps backing up re-exports nothing until a session actually changes.
Vectors, episodes, segments, outcomes and projects are never backed up — restore re-derives them. See Backup & Restore.
longhand doctor (add --json for machine-readable output) checks, in this order: the longhand CLI is on PATH; version freshness against PyPI (the one check that goes over the network — forced fresh on every doctor run, unlike the CLI's own cached once-daily check — unless LONGHAND_NO_UPDATE_CHECK disables it, in which case this row just reports itself disabled); the SessionEnd, Stop, and UserPromptSubmit hooks (flagging a stale pre-0.5.2 hook that used the removed $CLAUDE_TRANSCRIPT_PATH); the reconciler launchd job (macOS only); Claude Desktop MCP registration; Claude Code MCP registration (checked via ~/.claude.json directly, so a plugin-provided server can read as "not installed" here even though it works — #100); the resolved data directory and which source won; recent-ingest freshness over the last 7 days (green ≥90%, yellow ≥50%, red below that; since 1.3.1 a quiet transcript that grew after its last full ingest also keeps it from going green, with a pointer to reconcile --fix); hook errors over the last 7 days; transcript-format drift over the last 30 days; Codex capture status; count rows (sessions, events, projects, episodes); sessions still needing analysis (excluding archived-but-not-yet-finalized Codex sessions); the Codex finalizer's status; storage size in bytes; and aux/unknown event count. Since 1.3.0 a Backup row sits between Storage and Aux/unknown events: off, <mode> · never pushed, on · last push <age>, auto · last push <age>, or <mode> · last run FAILED <age> when the last run recorded an error (a run refused before it starts — no clone, a changed origin, a busy lock — isn't recorded).
ReplayEngine reconstructs a file's state from SQLite, not by replaying the JSONL line-by-line. It starts from the last Write at or before the target point (a Write sets full content authoritatively); if there is none, it starts from the first Edit's old_string instead — a fragment of the file as Claude Code first touched it, not necessarily the true original — and applies Edit (honoring replace_all), Write, and MultiEdit operations forward in order. If the session never edited the file at all, it falls back to the content captured by a Read of it (source: "read_snapshot"). This same engine backs the CLI's replay/diff, and the MCP replay_file and find_episodes(episode_id=…) detail mode.
-
Everything is local. SQLite and ChromaDB live in the resolved data directory (
~/.longhand/by default — relocatable since v0.13.0). No network calls happen during recall. - No summarization. Events are stored verbatim; the harness-bookkeeping entry types skipped by the parser are noise, not conversation content. The AI is never the gatekeeper of its own memory.
- Deterministic analysis. Rules-based, reproducible, same input → same output. No LLM in the ingest or analysis path — the CPU ONNX embedding model runs in both (it's a fixed, non-generative encoder, not a decision-maker), but nothing generates or infers text.
-
Fail-open hooks. Claude Code proceeds even if Longhand crashes inside a hook — enforced by
tests/test_hook_guarantees.py(never raise, never touch the network, never block the prompt). - Parameterized SQL everywhere. No string concatenation of user input into a query, no command-injection surface.
See Configuration → Storage paths for the full data-directory layout (SQLite files, chroma/, config.json, caches, logs, and their permissions). Backups (1.3.0+, opt-in) add backup/ (the clone), backup-state.json, backup.lock, and logs/backup.log.
-
A new extractor: add it under
longhand/extractors/, call it from wherever_extract_git_operations/error-detection are invoked in the ingest path, and add fixtures undertests/fixtures/transcript_shapes/(Claude Code) ortests/fixtures/codex_shapes/(Codex). Only the Claude Code corpus has tooling:scripts/harvest_entry_shapes.pyscans~/.claude/projectsand prints sanitized candidate lines for entry types the fixture doesn't cover yet, for a person to review and append totranscript_shapes/entries.jsonl— it has no Codex support, socodex_shapes/entries.jsonlfixtures are still written by hand. -
A new analysis pass: add a module under
longhand/analysis/, wire it intoLonghandStore.analyze_session, and remember it needs to be idempotent —analyze_sessiondeletes and rebuilds a session's derived data on every call. -
A new MCP tool: define its
Tool()schema inlist_tools()and add a matching entry to the_DISPATCHdict inmcp_server.py— a schema with no dispatch entry lists the tool but returns "Unknown tool" the moment it's called. Decide whether it needs amax_charscap (most read-heavy tools should), and add it toCLAUDE.md's decision tree if it changes which tool an agent should reach for first.