Documentation
¶
Overview ¶
Package ingest discovers Claude Code transcript files (~/.claude/projects/**), tails them, and turns their JSONL lines into normalized events. The transcript format is not a public contract: the parser is schema-versioned, tolerates unknown fields and line types, and skips malformed lines instead of failing. See .ai/03-contracts.md § Transcript JSONL (observed shape).
Index ¶
- Constants
- Variables
- func BackfillTitles(ctx context.Context, db *sql.DB, log *slog.Logger) (named int, err error)
- func BackfillToolMessageIDs(ctx context.Context, db *sql.DB, log *slog.Logger, after int64, limit int) (linked int, lastID int64, err error)
- func ClipAssistantText(s string) string
- func DefaultRoot() (string, error)
- func HasReplacementChar(s string) bool
- func MainTranscript(recorded, sessionID string) string
- func NeedsEmptyTextRepair(storedVersion string) bool
- func NeedsTextRepair(storedVersion string) bool
- func NeedsTitleBackfill(storedVersion string) bool
- func RepairAssistantText(ctx context.Context, db *sql.DB, log *slog.Logger) (repaired int, err error)
- func RepairEmptyAssistantText(ctx context.Context, db *sql.DB, log *slog.Logger) (repaired int, err error)
- type Line
- type Stats
- type Tailer
Constants ¶
const MaxAssistantText = event.MaxAssistantText
MaxAssistantText caps the assistant prose kept per turn. It exists to stop a pathological turn from bloating the database, not to summarise: the value is well above a normal closing summary so the thing people actually come back for — "what changed, and what I still need from you" — is stored whole.
It lives in package event so the store can apply the same cap when it folds a later line of one response into the stored turn (store.MergeAssistantText).
const SchemaVersion = 4
SchemaVersion is bumped whenever the parser's expectations of the transcript shape change. Stored with the daemon's meta so a future migration can decide whether historical events need re-derivation.
v2 (2026-08-20): assistant text is clipped on runes rather than bytes, at a much higher limit. Rows written by v1 may be short and may end in U+FFFD.
v3 (2026-09-29): `ai-title` lines are read into sessions.title. Rows from earlier versions are filled once by BackfillTitles.
v4 (2026-10-04): the prose on a response's later lines is folded into its turn (store.MergeAssistantText). Turns stored earlier without their text are filled once by RepairEmptyAssistantText.
const TypeAITitle = "ai-title"
TypeAITitle is the line Claude Code writes to name a session — the name its own /resume picker shows. It repeats through the transcript and carries no event; the tailer stores it as the session's title.
Variables ¶
var ErrMalformed = errors.New("malformed line")
ErrMalformed marks lines that are not valid JSON objects.
var ErrSkip = errors.New("skip line")
ErrSkip marks lines that carry nothing we consume (meta lines, blank lines).
Functions ¶
func BackfillTitles ¶ added in v0.59.0
BackfillTitles names the Claude Code sessions ingested before titles were read, from the transcripts still on disk.
The tailer resumes from a stored offset, so an `ai-title` line it passed before parser v3 is never read again; without this every session older than the upgrade would stay unnamed even though its name is sitting in the file. One read per transcript, the last title wins (Claude Code rewrites it as the conversation moves), and a transcript that is gone leaves the row alone.
func BackfillToolMessageIDs ¶ added in v0.14.0
func BackfillToolMessageIDs(ctx context.Context, db *sql.DB, log *slog.Logger, after int64, limit int) (linked int, lastID int64, err error)
BackfillToolMessageIDs recovers the tool→turn linkage for tool.pre rows written before per-directory attribution existed.
WHY THIS NEEDS THE TRANSCRIPTS. The link is the assistant message id: a tool_use block and the usage billed for it are content blocks of the same message. Historical tool.pre payloads never stored it — the parser only began writing `message_id` with this change — and it cannot be recovered from the database, because ordering by id does NOT recover it. One response is written as several assistant lines that each repeat the same usage; the store keeps only the first (key `msg:<id>`), so the tool_use blocks land AFTER the next distinct turn's row. Measured against transcript ground truth on the owner's database, nearest-preceding-turn gives the true message id for 1981 of 5115 tool calls (38.7%) — a systematic one-turn shift, not noise.
So the fact is read back from the file that still holds it. Rows whose transcript is gone keep a NULL msg_id and report as unattributed, which is the honest answer rather than a guessed one.
WHY PATHLESS CALLS ARE INCLUDED (OQ-10, decided 2026-08-23). The scan originally filtered on `touch_dir IS NOT NULL`, which was right while only per-directory attribution used the linkage: a call naming no file can never charge a directory, so scanning for it bought nothing. The work-kind breakdown joins on the SAME msg_id, and pathless calls are most of the tool calls — on the owner's database 53293 of 69555 tool.pre rows name no path, and Bash alone is 35161 of them. Filtered out, the breakdown reported 86.5% of 30-day spend as "no tool call" against a repaired 9.4%: the feature suppressed itself on exactly the database it was built for. The filter is therefore gone, and the only remaining requirement is a recorded transcript to read the fact back from.
THE LINK CANNOT BE WRONG, ONLY MISSING. A tool_use id is unique to the message that issued it: verified across all 1560 transcripts on the owner's machine, none of 69552 distinct tool_use ids appears under two message ids (2026-08-23). So a retry can never produce a different answer, and a row whose id is nowhere on disk keeps NULL rather than a guess.
It is idempotent and resumable: rows are taken in id batches, each batch is committed as it completes, and `after` resumes from the last id the caller stored. Only rows still NULL are considered, so a re-run costs a scan and changes nothing. Returns the highest event id examined, which the caller persists as the resume cursor.
func ClipAssistantText ¶ added in v0.64.0
ClipAssistantText applies the assistant-prose cap to text from another agent's transcript, so every source's `payload.text` is cut the same way.
func HasReplacementChar ¶ added in v0.9.0
HasReplacementChar is a small helper for tests and diagnostics.
func MainTranscript ¶ added in v0.59.0
MainTranscript is the file holding a session's own conversation.
A session's recorded transcript_path is whichever file its last line arrived on, and a subagent writes under `<project>/<session-id>/subagents/…`, so the recorded path often points into a subagent. The main thread is always `<project>/<session-id>.jsonl`.
func NeedsEmptyTextRepair ¶ added in v0.70.0
NeedsEmptyTextRepair reports whether rows were stored before the prose on a response's later lines was kept (RepairEmptyAssistantText).
func NeedsTextRepair ¶ added in v0.9.0
NeedsTextRepair reports whether the database was written by a parser version that truncated on bytes.
func NeedsTitleBackfill ¶ added in v0.59.0
NeedsTitleBackfill reports whether rows were ingested before titles were read. A fresh database ("") reads every line, titles included.
func RepairAssistantText ¶ added in v0.9.0
func RepairAssistantText(ctx context.Context, db *sql.DB, log *slog.Logger) (repaired int, err error)
RepairAssistantText re-derives the stored prose of assistant turns from the transcripts still on disk.
Parser v1 capped assistant text at 2000 *bytes* and sliced at an arbitrary byte offset. Two consequences: multi-byte prose (Cyrillic is two bytes per character) was cut at roughly half the intended length, and a cut through the middle of a rune left a U+FFFD at the end of about a fifth of clipped rows. The cap landed hardest on closing summaries — the one thing people come back to a session for.
Fixing the parser only helps lines ingested afterwards, so this walks the affected rows once and rewrites `payload.text` in place from the original transcript. It touches nothing else: no new events, no changed ids, no recomputed costs. Rows whose transcript has since been deleted keep what they have — a short note is better than a missing one.
func RepairEmptyAssistantText ¶ added in v0.70.0
func RepairEmptyAssistantText(ctx context.Context, db *sql.DB, log *slog.Logger) (repaired int, err error)
RepairEmptyAssistantText fills the prose of assistant turns that were stored without it, from the transcripts still on disk.
Claude Code writes one response as several lines, and the store keeps the first — which became a thinking line with no text once Claude Code started writing one ahead of every response. The prose on the lines after it was dropped (store.MergeAssistantText now keeps it). On the owner's database that was 93% of the turns stored after 2026-09-29.
Candidates are main-transcript turns with an empty `text`. Most of those legitimately have none — a response that only called a tool — and are left as they are when the transcript has no text for them either. Each session's recorded transcript is read, plus its own main file and subagent directory when the recorded path is elsewhere; never the whole project tree, which on a busy project is hundreds of files and this runs at startup.
Types ¶
type Line ¶
type Line struct {
Type string `json:"type"`
UUID string `json:"uuid"`
ParentUUID string `json:"parentUuid"`
SessionID string `json:"sessionId"`
PromptID string `json:"promptId"`
Cwd string `json:"cwd"`
Timestamp string `json:"timestamp"`
Version string `json:"version"`
GitBranch string `json:"gitBranch"`
IsSidechain bool `json:"isSidechain"`
AITitle string `json:"aiTitle"` // type "ai-title": Claude Code's own name for the session
AgentID string `json:"agentId"`
Subtype string `json:"subtype"`
DurationMs int64 `json:"durationMs"`
Message *struct {
Role string `json:"role"`
Model string `json:"model"`
ID string `json:"id"`
Content json.RawMessage `json:"content"`
Usage *struct {
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
CacheCreation *struct {
Ephemeral5m int64 `json:"ephemeral_5m_input_tokens"`
Ephemeral1h int64 `json:"ephemeral_1h_input_tokens"`
} `json:"cache_creation"`
} `json:"usage"`
} `json:"message"`
}
Line is the subset of a transcript line the parser understands.
func (*Line) Events ¶
Events converts a parsed line into zero or more normalized events. Keys are chosen to collide with the hook shim's keys for the same logical event ("pre:<tool_use_id>", "post:<tool_use_id>", "prompt:<prompt_id>"), so whichever plane arrives first wins and the other dedupes in the store.
type Stats ¶
type Stats struct {
FilesKnown int `json:"files_known"`
LinesParsed int64 `json:"lines_parsed"`
LinesMalformed int64 `json:"lines_malformed"`
LinesSkipped int64 `json:"lines_skipped"`
EventsStored int64 `json:"events_stored"`
EventsDeduped int64 `json:"events_deduped"`
BackfillDone bool `json:"backfill_done"`
}
Stats counts what the tailer has done (exposed on /v1/status).
type Tailer ¶
type Tailer struct {
Root string
Recorder *rollup.Recorder
Store *store.Store
Log *slog.Logger
// PollInterval is the fallback rescan cadence (fsnotify is best-effort and not
// recursive; new project directories and network filesystems need the poll).
PollInterval time.Duration
// BackfillWindow: files last modified longer ago than this are backfilled in
// the background after live files; zero means everything is treated as live.
BackfillWindow time.Duration
// MaxLine bounds one JSONL record: the bytes before its newline. A longer
// record is skipped without being held in memory (see readFile). The longest
// line in 4.0 GB of local transcripts was 2.1 MB (2026-10-18); a
// tool_result can embed a whole file, hence the headroom.
MaxLine int
// contains filtered or unexported fields
}
Tailer follows every *.jsonl under Root and records normalized events.