Documentation
¶
Overview ¶
Package ingest is the agent-agnostic ingest driver: byte-offset bookkeeping per source file, session upsert, message insertion, and chunking. It knows nothing about any particular agent's log format — that lives in a per-agent Adapter (internal/ingest/claudecode today, Codex later) that turns one raw log line into the normalized shapes below.
Index ¶
- Constants
- Variables
- func ChunkSession(db DBTX, sessionID string) error
- func IsInjectedUserText(text string) bool
- func Lock(lockPath string) (release func(), err error)
- func LockWait(ctx context.Context, lockPath string, poll time.Duration) (func(), error)
- func Run(db *sql.DB, adapter Adapter, path string) error
- func TitleFromPrompt(prompt string) string
- type Adapter
- type DBTX
- type FileResult
- type FileTouch
- type Freshness
- type ParseResult
- type RawMessage
- type Root
- type SessionUpdate
Constants ¶
const FreshnessQuiet = 2 * time.Minute
FreshnessQuiet is how long a log file must go unwritten before unread content in it counts as pending. The calling agent's own live session file is written on every turn, so without a quiet window the index would always look stale from inside any session, and the warning would be noise. Two minutes is long enough to skip a live session between turns' tool calls, and short enough that a real gap is still reported.
Variables ¶
var ErrIngestBusy = errors.New("another ctx process is already ingesting (ctx daemon, ctx ingest, or an MCP server catching up)")
ErrIngestBusy means another process holds the ingest lock.
Functions ¶
func ChunkSession ¶ added in v0.2.0
ChunkSession is chunkSession for callers outside this package. To rebuild a session's chunks from scratch, delete them first: chunking resumes after the last existing chunk.
func IsInjectedUserText ¶ added in v0.2.0
IsInjectedUserText reports whether text that arrived under role=user was actually written by the harness rather than the person.
Why it matters: the chunker starts a new chunk at every user text message, so an injected notification stored as a user turn becomes its own little "User: <task-notification>..." chunk. Those match common words in almost any query and crowd real exchanges out of search, and an injected block that happens to come first becomes the session's title. Like a mailroom that files the courier's delivery slip as if it were the customer's letter: the slip is kept, but it shouldn't be indexed as correspondence. Callers store such text as role=system, kind=event, which keeps it in messages (nothing is lost) but out of turn boundaries, chunks and titles.
func Lock ¶ added in v0.2.0
Lock takes the machine-wide ingest lock at lockPath without waiting, and returns a function that releases it.
Every ingest entry point takes it: `ctx daemon` for its whole life, `ctx ingest` for one run, and each MCP server's catch-up. Ingest is idempotent for ONE reader, but two processes reading the same log at the same moment both start from the same byte offset and number the same lines from a MAX(seq) that is moving under them, which stores those lines twice. Like two clerks working one in-tray: either one alone files every letter once, together they file some twice.
It is an operating-system lock (flock on Unix, LockFileEx on Windows), not a "this file exists" marker, so the OS releases it the moment its holder exits or crashes. There is no stale lock to detect and no takeover race. The lock file itself is left in place; only the lock on it comes and goes.
func LockWait ¶ added in v0.2.0
LockWait is Lock, retrying every poll until it succeeds or ctx ends. For the daemon, which must eventually own ingest even if it starts while an MCP server is midway through a catch-up.
func Run ¶
Run processes one log file: reads new bytes since the source's last byte offset, parses each complete line, upserts the session(s) it belongs to, inserts new messages, and chunks any turns that now look settled. A line that fails to parse is logged to sources.last_error and skipped — never fatal to the rest of the file.
func TitleFromPrompt ¶ added in v0.2.0
TitleFromPrompt is the fallback session title: the first user prompt, redacted, whitespace collapsed onto one line, cut to 80 characters.
Types ¶
type Adapter ¶
type Adapter interface {
// Agent is this adapter's value for sessions.agent / sources.agent,
// e.g. "claude-code".
Agent() string
// ParseLine parses one line (without its trailing newline) of the
// agent's log format.
ParseLine(line []byte) (ParseResult, error)
}
Adapter turns one agent's raw log format into the driver's normalized shapes. Implementations must never panic on malformed input — return an error instead, which the driver logs to sources.last_error and continues past.
type DBTX ¶ added in v0.2.0
type DBTX interface {
Exec(query string, args ...any) (sql.Result, error)
Query(query string, args ...any) (*sql.Rows, error)
QueryRow(query string, args ...any) *sql.Row
}
DBTX is what chunking needs from a connection: satisfied by both *sql.DB (ingest) and *sql.Tx (repair, which rebuilds chunks inside one transaction so an interrupted repair changes nothing).
type FileResult ¶
FileResult is one file's outcome from RunAll.
func CatchUp ¶ added in v0.2.0
CatchUp runs RunAll over every root while holding the ingest lock (see Lock). Several `ctx mcp` servers are often running at once, one per open agent session, and each catches up at startup; the lock makes all but one of them, and any of them while `ctx daemon` runs, back off with ErrIngestBusy instead of reading the same logs at the same moment.
Per-file failures don't stop the run; they are in the returned results (FileResult.Err), as with RunAll.
func RunAll ¶
RunAll walks root for *.jsonl files and calls Run on each, using a fresh Adapter per file. The factory (rather than a single shared instance) matters for an adapter like Codex's, whose log format carries no per-line session id — the adapter has to remember the current session id as state across ParseLine calls within one file, and reusing one instance across multiple files would leak that state between unrelated sessions.
A missing root (no sessions ingested yet on this machine) is not an error — it just yields no results.
type FileTouch ¶
type FileTouch struct {
Path string
Action string // 'read' | 'edit' | 'create' | 'delete' | 'rename'
}
FileTouch is "which file did this tool call touch, and how" — extracted by an adapter from a tool_call's structured input, not guessed from message text. Path may be absolute (as the tool reported it); the driver relativizes it against the session's cwd before storing it, since file_touches.path is project-relative.
type Freshness ¶ added in v0.2.0
type Freshness struct {
// LastIngestAt is the most recent time any source file was read, in
// ISO-8601 UTC. Empty if nothing has ever been ingested.
LastIngestAt string
// PendingFiles counts log files that have content ctx hasn't read yet:
// files it has never seen, or files that grew or shrank since it last
// read them. Files written to within the quiet window are not counted
// (see CheckFreshness).
PendingFiles int
// OldestPendingAt is the modification time of the longest-waiting
// pending file, in ISO-8601 UTC: roughly how far back the gap reaches.
OldestPendingAt string
}
Freshness says how far behind the agents' own logs the index is.
Without it, a search over a stale index looks exactly like a search over a quiet week: "no sessions after October 1" reads as "nobody worked after October 1" when really nobody ran ingest. Like a claims office that stamps every answer with "post opened up to: Tuesday 09:00", so a caller can tell "no claim on file" from "we haven't opened that day's mail yet".
func CheckFreshness ¶ added in v0.2.0
CheckFreshness compares each log file under roots with what the sources table says ctx has read from it. It only stats files and reads one query; it never opens a log file, so it is cheap enough to run on every search (about a thousand stat calls on a machine with months of sessions).
type ParseResult ¶
type ParseResult struct {
// Message is nil when the line carries only a session-level update (an
// ai-title event) and nothing to store in messages.
Message *RawMessage
Session SessionUpdate
// Skip is true for pure UI/harness bookkeeping (mode changes,
// permission-mode, environment attachments, ...) that isn't
// conversation and carries no session update either.
Skip bool
}
ParseResult is what an Adapter returns for one input line.
type RawMessage ¶
type RawMessage struct {
Role string // "user" | "assistant" | "system" | "tool" (messages.role)
Kind string // "text" | "tool_call" | "tool_result" | "thinking" | "event"
ToolName string // set for tool_call / tool_result; may be resolved later, see ToolUseID
ToolUseID string // present on tool_call and tool_result blocks; not persisted directly,
// used by the driver to correlate a tool_result back to the tool_call
// that produced it (the log format only carries the name on the call).
Content string // cleaned text, redacted before insert
Raw []byte // the original log line, redacted before insert
CreatedAt string // ISO-8601 UTC, from the log line's own timestamp
// FileTouches is set when this message is a tool_call the adapter
// recognizes as touching files (an edit, a read, a multi-file patch...),
// so the driver can also record them in file_touches. Left nil for everything else —
// most tool calls (a shell command, an unrecognized tool) don't name a
// file in a structured way an adapter can reliably extract.
FileTouches []FileTouch
}
RawMessage is one adapter-normalized event extracted from a single log line, ready for redaction and insertion into the messages table. Everything an agent's log format needs to express funnels through this shape so the driver never has to know which agent produced it.
type Root ¶ added in v0.2.0
Root is one agent's session tree: where its logs live and how to get a fresh Adapter for a file in it (fresh per file; see RunAll).
type SessionUpdate ¶
type SessionUpdate struct {
NativeID string // the agent's own session id — required on every non-skip line
CWD string
GitBranch string
GitCommit string
// CommitSource says how GitCommit was obtained (store.Source*). The
// driver fills it in when it resolves the commit itself.
CommitSource string
Version string
Model string
Title string
Timestamp string
}
SessionUpdate carries session-level fields discovered on a log line that isn't itself a conversational message (an agent-provided title event) or that ride along with one (cwd, branch, model). Zero-value fields mean "no new information" and leave the existing column alone.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package claudecode adapts Claude Code's session JSONL format (one JSON object per line under ~/.claude/projects/<sanitized-cwd>/<session-id>.jsonl) into the shapes internal/ingest knows how to store.
|
Package claudecode adapts Claude Code's session JSONL format (one JSON object per line under ~/.claude/projects/<sanitized-cwd>/<session-id>.jsonl) into the shapes internal/ingest knows how to store. |
|
Package codex adapts Codex CLI's rollout JSONL format (one JSON object per line under ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl) into the shapes internal/ingest knows how to store.
|
Package codex adapts Codex CLI's rollout JSONL format (one JSON object per line under ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl) into the shapes internal/ingest knows how to store. |