ingest

package
v0.45.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
const MaxAssistantText = 16000

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.

View Source
const SchemaVersion = 2

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.

Variables

View Source
var ErrMalformed = errors.New("malformed line")

ErrMalformed marks lines that are not valid JSON objects.

View Source
var ErrSkip = errors.New("skip line")

ErrSkip marks lines that carry nothing we consume (meta lines, blank lines).

Functions

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 DefaultRoot

func DefaultRoot() (string, error)

DefaultRoot returns ~/.claude/projects.

func HasReplacementChar added in v0.9.0

func HasReplacementChar(s string) bool

HasReplacementChar is a small helper for tests and diagnostics.

func NeedsTextRepair added in v0.9.0

func NeedsTextRepair(storedVersion string) bool

NeedsTextRepair reports whether the database was written by a parser version that truncated on bytes.

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.

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"`
	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 ParseLine

func ParseLine(raw []byte) (*Line, error)

ParseLine decodes one JSONL line. Unknown fields are ignored by encoding/json.

func (*Line) Events

func (l *Line) Events(fallbackTs time.Time) []event.Event

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.

func (*Line) Ts

func (l *Line) Ts(fallback time.Time) time.Time

Ts parses the RFC 3339 timestamp; falls back to `fallback` when absent/invalid.

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 line (a tool_result can embed a whole file).
	MaxLine int
	// contains filtered or unexported fields
}

Tailer follows every *.jsonl under Root and records normalized events.

func New

func New(root string, rec *rollup.Recorder, st *store.Store, log *slog.Logger) *Tailer

New creates a tailer with defaults.

func (*Tailer) Run

func (t *Tailer) Run(ctx context.Context) error

Run tails until ctx is cancelled. It first processes live files (modified within BackfillWindow), then backfills older history in the background while continuing to follow live files.

func (*Tailer) Stats

func (t *Tailer) Stats() Stats

Stats returns a snapshot of counters.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL