ingest

package
v0.11.2 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 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 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