store

package
v0.159.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 38 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 store owns the SQLite database: opening, migrating, and every query. Nothing else in Caprock issues SQL. Pure Go driver (modernc.org/sqlite), no CGO — see ADR-012.

Index

Constants

View Source
const (
	BrainIdea     = "idea"
	BrainDecision = "decision"
	BrainFinding  = "finding"
	BrainQuestion = "question"
	BrainTopic    = "topic"
	BrainPerson   = "person"
	BrainProject  = "project"
)

Node kinds. The first four are memories, then a note imported from an Obsidian vault (BrainNote, brainvault.go); the last three are entities, which exist once per normalized title.

View Source
const (
	EdgeRelates     = "relates"
	EdgeFollows     = "follows"
	EdgeContradicts = "contradicts"
	EdgePartOf      = "part_of"
	// EdgeSupersedes goes from a newer decision to the older one it
	// replaces (migration 0069): the older one is no longer current.
	EdgeSupersedes = "supersedes"
)

Edge kinds.

View Source
const (
	BrainTitleRunes   = 80
	BrainSummaryRunes = 400
)

Limits on what one node holds: a title is a line, a summary a paragraph.

View Source
const (
	BrainKeywordsMax  = 8
	BrainKeywordRunes = 40
)

BrainKeywordsMax caps a memory's keywords, and BrainKeywordRunes each one.

View Source
const (
	BrainGapPending = "pending"
	BrainGapDone    = "done"
	BrainGapFailed  = "failed"
)

Brain gap statuses, as the CHECK constraint spells them.

View Source
const (
	BrainRunOK      = "ok"
	BrainRunFailed  = "failed"
	BrainRunSkipped = "skipped"
)

Brain run statuses, as the CHECK constraint spells them.

View Source
const (
	// BrainSkipAutomation marks a session started with `automation: true`
	// (POST /v1/agents): a scheduled job's run, which Second Brain never
	// reads. Written at the spawn, before the session's first event, as the
	// extraction's own record that it was told not to read this session;
	// BrainCandidates leaves such a session out. It is not a column on the
	// session: the extraction is the only reader of the mark.
	BrainSkipAutomation = "automation"
	// BrainSkipExcluded is the prefix of the reason for a session in a
	// folder the user excluded (Settings → Second Brain); the folder follows.
	BrainSkipExcluded = "excluded"
	// BrainSkipRootOrHome is the prefix of the reason for a session started
	// at a filesystem root or in the home directory itself (RootOrHome):
	// where launchd and cron start a scheduled `claude -p`, and nobody keeps
	// a project. The cwd follows ("root or home: /"). Like the automation
	// mark it is for good — a session's cwd does not change — so
	// BrainCandidates leaves such a session out from then on.
	BrainSkipRootOrHome = "root or home"
)

Reasons a read is recorded as skipped before anything is sent, in BrainRun.Error. A reason that names its cause carries it after a colon ("excluded: /Users/u/dev/ops"); the prefixes are what a screen reads.

View Source
const (
	BrainHandoffDecisions     = 15
	BrainHandoffDecisionRunes = 1500
	BrainHandoffMax           = 5
	BrainHandoffRunes         = 700
	BrainHandoffSummary       = 160
)

What Second Brain adds to a new session's handoff (ADR-063), each part in a budget of its own so the passage before them is never cut to make room:

  • the repository's current decisions (nothing supersedes them), newest first, at most BrainHandoffDecisions, one line each — "#id title" — in BrainHandoffDecisionRunes. Fifteen titles of up to 80 runes fit.
  • then its other memories, pinned first, then newest, at most one per source session (so one long session cannot fill it), at most BrainHandoffMax, titles with the summary clipped to BrainHandoffSummary, in BrainHandoffRunes. A superseded memory and a decision already listed are left out.
View Source
const (
	// MetaPayloadCompactCursor is the highest event id the compaction has
	// examined, or PayloadCompactDone once it has examined them all.
	MetaPayloadCompactCursor = "payload_compact_cursor"
	// MetaPayloadCompactUntil is the highest event id when the compaction
	// began: every row after it was written through CapToolField already, so
	// the pass has an end however much is recorded while it runs.
	MetaPayloadCompactUntil = "payload_compact_until"
	// PayloadCompactDone is the cursor's value once the pass is complete.
	PayloadCompactDone = "done"
)

Payload compaction: the base64 that rows stored before event.CapToolField still hold, replaced by the marker CapToolField writes now.

CapToolField bounds what is written from 2026-10-13 on; the rows written before it keep every screenshot as base64. On the owner's machine that was most of a 2.2 GB file, and nothing reads it back: no screen renders a stored image (the chat's image upload is base64 on its way in, never read from the database). Only the base64 goes — long text is kept as it was, unlike on the write path, because a row already stored is someone's history.

The daemon runs it a step at a time while idle (internal/daemon/compact.go). Each step reads a window of ids outside any transaction, rewrites the rows that held base64 in one short transaction, and moves the cursor in the same one, so a stopped daemon resumes where it was and a finished pass is never read again.

View Source
const (
	// RepoAgentDays is the comparison window of both figures.
	RepoAgentDays = 14
	// RepoTeamDays is the team chart's window: a month, as a contributors
	// chart reads.
	RepoTeamDays = 30
	// RepoAgentNowMs is "now": the burn's own ten minutes.
	RepoAgentNowMs = 10 * 60 * 1000
)
View Source
const (
	ProjectKindRepo   = "repo"
	ProjectKindFolder = "folder"

	ProjectSourceSeed    = "seed"
	ProjectSourceSession = "session"
	ProjectSourceFolder  = "folder"
	ProjectSourceNew     = "new"
	ProjectSourceClone   = "clone"
)

Project kinds and sources, as the CHECK constraints spell them.

View Source
const (
	StatusActive = "active"
	StatusIdle   = "idle"
	StatusEnded  = "ended"
)

Session status values.

View Source
const (
	HandoffNone     = 0 // nothing was there to hand over
	HandoffServed   = 1 // it was handed what the last session left
	HandoffWithheld = 2 // something was there and was held back, as the control
)

Handoff states on sessions.handoff.

View Source
const (
	SavedKindPrompt  = "prompt"
	SavedKindCommand = "command"
)

Saved prompt kinds, as the CHECK constraint spells them.

View Source
const (
	MetaSchemaVersion = "schema_version"
	// MetaTranscriptSchema records the parser version that wrote the events, so
	// a bump can trigger a one-time re-derivation of affected payloads.
	MetaTranscriptSchema = "transcript_schema_version"
	MetaPricingVersion   = "pricing_version"
	// MetaToolLinkBackfilled marks the one-time recovery of the tool→turn
	// linkage from the transcripts (ingest.BackfillToolMessageIDs). It lives in
	// the daemon rather than the store because it needs the transcript files.
	//
	// It is the marker for the ORIGINAL, path-only pass and is now only read as
	// history: a database that finished that pass still has every pathless call
	// unlinked, so it must not be taken to mean the linkage is complete.
	MetaToolLinkBackfilled = "tool_link_backfilled"
	// MetaToolLinkCursor is the resume point of the widened backfill (OQ-10):
	// the highest event id already examined. A separate key from
	// MetaToolLinkBackfilled because the narrow pass set that one to "1" on
	// databases where 53293 pathless rows were never even looked at — reusing
	// it would skip exactly the machines the widening is for. Absent ⇒ start at
	// 0; the sentinel below ⇒ finished.
	MetaToolLinkCursor = "tool_link_cursor"
	// MetaCodexDailyRebuilt marks that daily_stats' Codex rows were rebuilt
	// from events once — migrations 0022 and 0023 re-imported every Codex
	// event without taking the first import back out of daily_stats.
	MetaCodexDailyRebuilt = "codex_daily_rebuilt"
	// MetaCodexSeen remembers which Codex transcripts have been read (path,
	// modification time, size, session), so a restart reads only what changed.
	MetaCodexSeen = "codex_seen"
	// MetaCodexTextBackfilled marks that the Codex turns imported before the
	// importer read assistant prose have been given it from their transcripts
	// once (codex.Ingester.backfillText).
	MetaCodexTextBackfilled = "codex_text_backfilled"
	// MetaCodexChatBackfilled marks that the Codex transcripts read before
	// prompts and tool results were stored have been read once more for both
	// (codex.backfillChat).
	MetaCodexChatBackfilled = "codex_chat_backfilled"
	// MetaCodexSplitRepaired marks that the Codex rows earlier versions stored
	// wrongly have been repaired from the transcripts once: threads imported
	// from another agent removed, and subagent turns moved off the parent's
	// line-number keys (codex.Ingester.repairSplit).
	MetaCodexSplitRepaired = "codex_split_repaired"
	// MetaSessionModelRepaired marks that sessions.model was recomputed once
	// from each session's latest main-thread turn: earlier versions let a
	// subagent's turn overwrite it (rollup.RepairSessionModels).
	MetaSessionModelRepaired = "session_model_repaired"
	// MetaForkedTurnsRepaired marks that the assistant turns a fork's
	// transcript copied from its parent have had their usage and cost taken
	// back out once: earlier versions priced every copy again
	// (rollup.RepairForkedTurns).
	MetaForkedTurnsRepaired = "forked_turns_repaired"
	// MetaDeepseekInjectedRemoved marks that the prompts earlier versions
	// stored for DeepSeek Harness's own `user/message` records (instructions,
	// runtime context) have been deleted once, verified against the
	// transcripts (deepseek.Ingester.removeInjected).
	MetaDeepseekInjectedRemoved = "deepseek_injected_removed"
	// MetaReportWeek is the ISO week of the last weekly report that was sent,
	// as "2026-W36". It lives here rather than in memory because an in-memory
	// marker sends a second copy of the message after every restart — the bug
	// cap.Guard.firedOn has, tolerable for a cap and not for a message someone
	// receives on their phone.
	MetaReportWeek = "report_week"
	// MetaReportLastError is why the last weekly send failed, empty when it did
	// not. Stored rather than held in memory for the same reason the week is:
	// the person who configured a bot is waiting for a message, not watching a
	// settings screen, and an error that vanishes on the next restart takes the
	// only evidence of a silent failure with it. "chat not found" a week later
	// is still the answer.
	MetaReportLastError = "report_last_error"
	// MetaAliveAt is the daemon's heartbeat, unix ms as a string, written every
	// minute. Read once at start, before the first write, it is when the
	// previous run stopped — to the minute, whether it stopped cleanly or the
	// machine went down under it.
	MetaAliveAt = "daemon_alive_at"
	// MetaInterrupted is the sessions that were still running when the daemon
	// last stopped and were gone when it started again, as JSON
	// {"stopped_at": ms, "ids": [...]} (FB-038).
	MetaInterrupted = "interrupted"
	// MetaReportLastSent is when a report last went out, unix ms as a string.
	MetaReportLastSent = "report_last_sent"
	// MetaEmptyTextRepairPending is "1" while assistant turns stored before
	// parser v4 still wait to have their prose read back from the transcripts
	// (ingest.RepairEmptyAssistantText). Set when a start finds an older
	// parser version, cleared when the repair has run, so a daemon stopped
	// mid-repair runs it again.
	MetaEmptyTextRepairPending = "empty_text_repair_pending"
	// MetaPRsBackfilled is "1" once session_prs holds the pull requests of the
	// events stored before migration 0035.
	MetaPRsBackfilled = "session_prs_backfilled"
	// ToolLinkDone is the MetaToolLinkCursor value meaning "no rows left".
	// A cursor alone cannot say so: the pass ends by reading a short batch, and
	// new unlinked rows never appear behind the cursor.
	ToolLinkDone = "done"
)

Meta keys.

View Source
const (
	// TrendDays is the comparison window.
	TrendDays = 14
	// TrendBucketMs is the scan's grain. Five minutes divides every UTC
	// offset in use (all are multiples of fifteen), so a bucket never
	// straddles a local midnight; a day's cut is at most one bucket late.
	TrendBucketMs = 5 * 60 * 1000
	// TrendBurnWindowMs is the burn window, the same ten minutes as the
	// "Burn now" figure it is compared with: two buckets.
	TrendBurnWindowMs = 10 * 60 * 1000
)
View Source
const (
	// UsualDays is the window the usual is measured over.
	UsualDays = 30
	// UsualMinCalls is how many priced calls make a session-hour active:
	// fewer is a session touched in passing, whose hour would drag the
	// median down without being a rate anyone worked at.
	UsualMinCalls = 5
	// UsualMinHours and UsualMinSessions are the samples below which a
	// distribution is not given at all.
	UsualMinHours    = 20
	UsualMinSessions = 8
)
View Source
const AutoVacuumIncremental = 2

AutoVacuumIncremental is PRAGMA auto_vacuum's value for INCREMENTAL.

View Source
const BrainAgentsMayRead = brainAgentsMayRead

BrainAgentsMayRead is brainAgentsMayRead for code outside the store that selects from brain_nodes as n.

View Source
const BrainCluster = "Obsidian"

BrainCluster is the project a note is put under when no folder on its path is named like a Caprock project.

View Source
const BrainEdgeWeightMax = 10

BrainEdgeWeightMax caps an edge's weight, so one busy pair cannot outweigh the whole graph.

View Source
const BrainGraphMax = 5000

BrainGraphMax is the most memories one graph read returns.

View Source
const BrainNearDuplicate = 0.75

BrainNearDuplicate is how alike two titles' words must be — shared words over all their words (Jaccard), folded — for a new memory to be the same as one already kept: "Scout stays read-only" and "The scout stays read-only" are 0.8.

View Source
const BrainNote = "note"

BrainNote is the node kind an imported note gets when no node with its title or an alias already exists. It is a memory-like node, never an entity.

View Source
const BrainRetagSession = "caprock:retag"

BrainRetagSession is the brain_runs.session_id of a re-tag batch. No session has it: a session id is a UUID or an agent's own id, never this.

View Source
const CodexRateLimitPrefix = "codex_"

CodexRateLimitPrefix namespaces Codex's windows in rate_limit_latest, so they sit beside Claude Code's `five_hour` / `seven_day` rows without replacing them: `codex_five_hour`, `codex_seven_day`.

View Source
const JournalSizeLimit = 64 << 20

JournalSizeLimit is the size, in bytes, the WAL is truncated to after a checkpoint (PRAGMA journal_size_limit). See Open.

View Source
const LiveSubagentWindow = 30 * time.Minute

LiveSubagentWindow bounds how long a silent subagent is believed to be working: one whose SubagentStop never arrived must not count forever.

View Source
const MainThreadWhere = `COALESCE(e.agent_id, '') = '' AND json_extract(e.payload, '$.sidechain') IS NOT 1`

MainThreadWhere keeps the events of a session's main thread and drops its subagents', for a query over `events e`. It is the SQL twin of event.Event.Subagent and must say the same thing.

View Source
const MaxEventPage = 5000

MaxEventPage is the most events one ListEvents call will return. Callers that need more must paginate with `after`.

View Source
const MaxSessionCalls = 20000

MaxSessionCalls bounds GET /v1/sessions/{id}/calls. A long session makes a few thousand model calls; this is several times that, and still a page the cockpit draws in one pass.

View Source
const MaxSessionsPage = 2000

MaxSessionsPage caps one page of the session list. The Now screen asks for more in steps; a caller asking for everything gets this many and the total in X-Total-Count, not a response the size of the database.

View Source
const MetaBrainScrubbed = "brain_secrets_scrubbed"

MetaBrainScrubbed marks that the memories and note excerpts stored before the privacy filter have been scrubbed once (ScrubBrainSecrets).

View Source
const MetaProjectsSeeded = "projects_seeded"

MetaProjectsSeeded is "1" once the projects list has been seeded from the repositories sessions ran in.

View Source
const OutsidePath = "\x00outside"

OutsidePath is the sentinel for turns whose carried directory is real but sits outside the repository — Claude's notes about the project, subagent scratchpads, test-output directories, or another checkout entirely.

It is a row of its own, sibling to the directory rows and to UnattributedPath, because it is neither: the work has a known location and that location is simply not in this tree. Merging it into repository-wide work would mislabel a quarter of the bill as "no single home" when its home is known and named; folding it into the repository root would claim work happened in the checkout that did not. See AttributeDir for the measured shares and for why "another checkout" is not split out separately.

View Source
const OverlapWindowMs = 30 * 60 * 1000

OverlapWindowMs is how far back "edited by both" looks: half an hour.

View Source
const SlowQuery = 300 * time.Millisecond

SlowQuery is how long one statement may take before it is logged.

Why the log exists. The owner's daemon twice read 1–1.7 GB from disk within a minute, a quarter of an hour apart (2026-10-13), and nothing on record said which code did it: the dashboard's requests, a startup repair and the storage measurement all read the same file through the same pool. Every statement now goes through a timed connection, so the next spike names its caller in the log instead of being reconstructed from guesses.

The time is wall time from the statement's start until its rows are closed, so it includes what the caller did between rows. That is deliberate: a result set held open for a second keeps a read snapshot (and the WAL behind it) for that second whatever the reason.

View Source
const TouchRule = "" /* 454-byte string literal not displayed */

TouchRule is the statement of how a turn is placed, shown in the UI so the number is not a black box. It is the sentence that makes this honest rather than a guess, so it says exactly what the rule does and claims nothing more.

THE RULE, in the user's words: a turn counts toward the directory of the most recent file it touched, and work keeps counting there until it touches a file somewhere else.

Why a stretch and not a single call. Work happens in stretches: after "finish /app", Claude edits, runs the tests, reads the output, greps, edits again. Charging only the calls that name a file would count the edit and discard the hour around it.

What counts as touching. A tool that names a FILE — Read, Edit, Write, NotebookEdit. Bash does not, even when its command contains a path: `grep -r foo /services` reads a tree and `cd /services/api && go build ./...` names one directory while touching many, so parsing intent out of a command line would be inference presented as measurement. Under carry-forward that costs nothing, because a Bash turn is placed by the file touched before it rather than dropped.

Why reading counts. Reading a file to understand it is how most of a turn's tokens get spent — the contents enter the prompt and are billed.

View Source
const UnattributedPath = "\x00unattributed"

UnattributedPath is the sentinel for the turns carry-forward cannot place: those that ran before any file was touched in their session.

It is a sentinel, not a path, and it must never reach a user as one: the UI renders it as "repository-wide work" in its own style with the reason attached. It starts with a character no path segment does so that a hypothetical directory of the same name could not collide with it.

WHAT NOW LANDS HERE, AND WHY THE ROW IS SMALL. Under the previous strict rule this bucket was most of the money — 87.6% of the owner's `amarketer` — and the UI had to work hard to explain that it was not a failure. Under carry-forward it means one narrow, honest thing: a session's opening turns, before Claude has touched any file. On the owner's database that is $2.39 of $3426 in `amarketer` and $11.45 of $1729 in `caprock` (measured 2026-08-22). It is usually zero, and the UI must not render an empty row.

View Source
const WorkKindRule = "" /* 456-byte string literal not displayed */

WorkKindRule is the statement of how a turn is placed, shown in the UI so the number is not a black box — the same contract TouchRule holds for the per-directory breakdown.

The precedence is ordered by what the turn most concretely DID, strongest evidence first: writing a file is a stronger statement about a turn than running a command, which is stronger than reading. It is not ordered by cost, which would let the ranking rewrite itself as the data changed.

View Source
const WorktreeDir = ".caprock-worktrees"

WorktreeDir is where Caprock checks out a worktree for one of its own agents, relative to the repository root. Kept here so the resolver and the code that creates them agree on the name (see internal/agents.WorktreeDir).

Variables

BrainEdgeKinds lists every edge kind.

BrainKinds lists every node kind, memories and notes first.

View Source
var ErrBrainDuplicate = errors.New("there is already one with that title")

ErrBrainDuplicate is returned when a rename would give an entity the title of another of its kind.

View Source
var ErrBrainInvalid = errors.New("invalid memory")

ErrBrainInvalid wraps a node that cannot be stored as asked.

View Source
var ErrBrainNotFound = errors.New("no such memory")

ErrBrainNotFound is returned for an id no node has.

View Source
var ErrDuplicate = errors.New("duplicate event")

ErrDuplicate is returned by InsertEvent when (session_id, key) already exists.

View Source
var ErrInboxNotFound = errors.New("no such saved item")

ErrInboxNotFound is returned for an id no row has.

View Source
var ErrModuleDocNotFound = errors.New("no such document")

ErrModuleDocNotFound is returned for a document no row holds.

View Source
var ErrNotMultiRepo = errors.New("this project is not a multi-repo project")

ErrNotMultiRepo is returned when a multi-repo action meets a project with no member repositories.

View Source
var ErrProjectNotFound = errors.New("no such project")

ErrProjectNotFound is returned for an id no row has.

View Source
var ErrQueuedNotFound = errors.New("no such queued message")

ErrQueuedNotFound is returned for an id the session's queue does not hold.

View Source
var ErrRemovedSession = errors.New("session was removed from Caprock")

ErrRemovedSession is returned by the recorder for an event of a session the owner removed; it is not a failure, the event is simply not recorded.

View Source
var ErrSavedNotFound = errors.New("no such saved prompt")

ErrSavedNotFound is returned for an id no row has.

View Source
var ErrVaultExists = errors.New("that vault is already imported")

ErrVaultExists is a vault added twice.

View Source
var ErrVaultNotFound = errors.New("no such vault")

ErrVaultNotFound is an id no vault has.

Functions

func ActivityBuckets added in v0.108.0

func ActivityBuckets(ctx context.Context, q Querier, from, bucket int64, n int) (map[string][]int, error)

ActivityBuckets is how many turns and tool calls each session recorded in each bucket of [from, from+n*bucket): the sidebar's per-project sparkline. One range scan on idx_events_ts over a short window — the last hour by default — and only two kinds, so a busy machine reads a few thousand rows. Sessions with nothing in the window are absent.

func AddDaily

func AddDaily(ctx context.Context, q Querier, day, project, model string, tokens int64, cost float64, newSession bool) error

AddDaily increments daily_stats for (day, project, model). newSession bumps the sessions count, and is true only for the row that carries it — see MarkDailySession.

func AdvanceBrainGap added in v0.148.0

func AdvanceBrainGap(ctx context.Context, q Querier, id, cursor, now int64) error

AdvanceBrainGap records one read of a gap: its cursor moves on, the failures in a row are forgotten, and once read through the gap is done, its total what it took.

func ArchiveProject added in v0.75.0

func ArchiveProject(ctx context.Context, q Querier, id int64, at int64) error

ArchiveProject takes a project off the list. Nothing on disk is touched.

func AttributeDir added in v0.14.0

func AttributeDir(t TouchDirs, repoRoot string) (string, bool)

AttributeDir decides which row a turn's cost belongs to, given the directory carried into it and the repository the turn's session sits in.

It always returns a row, because every turn's cost belongs somewhere and the rows must sum to the repository total. There are exactly three outcomes:

  • a directory inside the repository, written relative to its root
  • OutsidePath, when the carried directory is real but not in this repository
  • UnattributedPath, when no touch preceded this turn in its session

PATHS OUTSIDE THE REPOSITORY get their own row rather than being folded into the repository root or dropped. Folding them into "/" would claim work happened in the checkout when it did not; dropping them would stop the parts reconciling with the total. On the owner's database this is not a rounding error — it is 25.8% of `amarketer` and 28.7% of `caprock` (measured 2026-08-22) — and it is overwhelmingly work ON this project whose files live elsewhere: Claude's own notes under ~/.claude/projects/<project>/memory, subagent scratchpads under the per-session temp directory, and test output directories. A share that large must be named, not hidden.

It deliberately does NOT try to tell "another checkout" from "scratch space". The only way to do so would be to ask whether the path sits under some OTHER repository root the database happens to know, and that answer is unstable: `caprock-web` is a real git repository on disk that no session was ever launched from, so it is invisible here — the same path would classify one way today and another tomorrow, silently moving money between rows. One structural question ("is it inside THIS repository?") is answerable from the two paths alone and always gives the same answer.

TURNS BEFORE ANY TOUCH land in UnattributedPath rather than carrying BACKWARD from the session's first touch. Measured both ways on the owner's database (2026-08-22, all time): carrying backward moves $2.39 of $3426 in `amarketer` and $11.45 of $1729 in `caprock` — 0.1% and 0.7%. That is far too little to justify a second rule pointing the opposite way, which would make the one-sentence explanation two sentences and let a session's opening question charge a directory it had not reached yet.

func AttributeTaskCost

func AttributeTaskCost(ctx context.Context, q Querier, taskID string) (float64, error)

AttributeTaskCost sums event cost within a task's assignment windows and writes it to tasks.cost_usd (T24).

func BootTime added in v0.60.0

func BootTime() time.Time

BootTime is when the machine last started, or the zero time when the platform cannot say.

It closes the one hole in ProcessAlive that is not rare: a reboot. The pid space starts again from the bottom, so the small numbers Claude Code sessions held yesterday are handed straight back out to whatever starts first, and a session from before the reboot was called alive for as long as that stranger ran. No process from before a boot can be running after it, so a session last heard from before the boot is over whatever its pid says.

func BrainAgentNodes added in v0.135.0

func BrainAgentNodes(ctx context.Context, q Querier, ids []int64) (map[int64]bool, error)

BrainAgentNodes returns the selected nodes that may reach an MCP client.

func BrainAutomation added in v0.157.0

func BrainAutomation(ctx context.Context, q Querier, sessionID string) (bool, error)

BrainAutomation reports whether a session carries the automation mark.

func BrainAutomationSince added in v0.157.0

func BrainAutomationSince(ctx context.Context, q Querier, since int64) (int, error)

BrainAutomationSince counts the sessions marked as automation since a moment (by when the mark was written, which is the spawn).

func BrainCatchUp added in v0.148.0

func BrainCatchUp(ctx context.Context, q Querier) (done, total, left int, err error)

BrainCatchUp is the catch-up's progress over every measured gap: the reads made, the reads in all, and how many gaps are left to read.

func BrainCostSince added in v0.122.0

func BrainCostSince(ctx context.Context, q Querier, since int64) (float64, error)

BrainCostSince is what the extraction's reads and re-tag batches cost since a moment, in US dollars, as claude reported each (its `total_cost_usd`, at API list price).

func BrainDecisionLine added in v0.148.0

func BrainDecisionLine(n BrainNode) string

BrainDecisionLine is how a decision is shown to a read or handed to a session: its id and title, one line.

func BrainEntityByNorm added in v0.135.0

func BrainEntityByNorm(ctx context.Context, q Querier, kind, norm string) (int64, error)

BrainEntityByNorm returns the id of the entity of a kind with a normalised title, 0 when there is none.

func BrainEntityTitles added in v0.117.1

func BrainEntityTitles(ctx context.Context, q Querier, kind string, limit int) ([]string, error)

BrainEntityTitles returns the titles of the entities of a kind that the most edges reach, for the extraction to link new memories to what exists. A topic an import made from a vault whose notes may not reach agents is left out: its name is the user's own tag (ADR-079).

func BrainFailures added in v0.117.2

func BrainFailures(ctx context.Context, q Querier, sessionID string) (int, int64, error)

BrainFailures is how many regular reads of a session have failed since its last one that did not, and when the latest failed (unix ms).

func BrainGapTokensPerRead added in v0.148.0

func BrainGapTokensPerRead(ctx context.Context, q Querier) (int64, error)

BrainGapTokensPerRead is the mean tokens of the catch-up reads that succeeded, 0 before the first.

func BrainGraphCounts added in v0.122.0

func BrainGraphCounts(ctx context.Context, q Querier) (topics, links int, err error)

BrainGraphCounts is how many topics the graph holds and how many links join one memory to another. A memory's link to its topic or project is not counted: nearly every memory has one, and counting them made the figure read as connections between memories that were never drawn.

func BrainHandedSince added in v0.122.0

func BrainHandedSince(ctx context.Context, q Querier, since int64) (sessions, memories int, err error)

BrainHandedSince counts the sessions started since a moment that were handed Second Brain memories, and how many memories that was in all.

func BrainLastRead added in v0.122.0

func BrainLastRead(ctx context.Context, q Querier) (int64, error)

BrainLastRead is when the newest read of a session that kept something finished, unix ms; 0 before the first. A re-tag batch is not a read.

func BrainNodeVaults added in v0.135.0

func BrainNodeVaults(ctx context.Context, q Querier, ids []int64) (map[int64]string, error)

BrainNodeVaults returns, for each of the nodes that has a note row, the name of the vault of its oldest one: the mark a screen draws.

func BrainNoteNodeAlone added in v0.135.0

func BrainNoteNodeAlone(ctx context.Context, q Querier, nodeID int64) (bool, error)

BrainNoteNodeAlone reports whether a node is a note node no note row marks: one whose only source just left.

func BrainProjectNames added in v0.135.0

func BrainProjectNames(ctx context.Context, q Querier) ([]string, error)

BrainProjectNames returns the names Caprock knows projects by: the projects' own and the sessions' — what a vault's folder is matched against.

func BrainRetagCursor added in v0.148.0

func BrainRetagCursor(ctx context.Context, q Querier) (int64, error)

BrainRetagCursor is the highest memory id a re-tag batch went through without failing (answered, or given up): the re-tag goes on above it.

func BrainRetagDone added in v0.148.0

func BrainRetagDone(ctx context.Context, q Querier) (int, error)

BrainRetagDone is how many memories the re-tag has given keywords.

func BrainSearchDoc added in v0.120.0

func BrainSearchDoc(title, summary, project string, keywords ...string) string

BrainSearchDoc is what brain_nodes.search holds for a node: its folded title, summary and project, one per line, the title first, and its keywords on a fourth line when it has any.

func BrainSessionInfo added in v0.120.0

func BrainSessionInfo(ctx context.Context, q Querier, sessionID string) (title, agent string, lastEventAt int64, err error)

BrainSessionInfo is what a screen names a session by while it is read: its own title (or first stored prompt), agent and the time of its last event. A session that is not there gives empty values, not an error.

func BrainSpendStart added in v0.148.0

func BrainSpendStart(now time.Time, days int) time.Time

BrainSpendStart is local midnight days-1 days before now's: where a chart of `days` days, today the last, begins.

func BrainSupersede added in v0.148.0

func BrainSupersede(ctx context.Context, q Querier, newer, older int64, now int64) error

BrainSupersede records that memory newer replaces older. Both must exist, be in the same project and be memories; older must be a decision. Anything else is ErrBrainInvalid, so a model's stray id cannot retire a memory elsewhere.

func BrainTitlesNear added in v0.148.0

func BrainTitlesNear(a, b string) bool

BrainTitlesNear reports whether two titles say the same thing by their words: at least two words each, and a Jaccard overlap of BrainNearDuplicate or more. A title in a script written without spaces is one word, so only the same title is near it.

func BrainTokensPerRead added in v0.148.0

func BrainTokensPerRead(ctx context.Context, q Querier, since int64) (int64, int, error)

BrainTokensPerRead is the mean tokens of the reads that asked claude and spent something since a moment, and how many there were: what a catch-up's days left are counted from. A re-tag batch is no read of a session and is left out. 0, 0 before the first.

func BrainTokensSince added in v0.117.2

func BrainTokensSince(ctx context.Context, q Querier, since int64) (int64, error)

BrainTokensSince is what the extraction's reads and re-tag batches have spent since a moment, input and output together.

func BrainVaultClaims added in v0.135.0

func BrainVaultClaims(ctx context.Context, q Querier, vaultID int64) (map[BrainClaim]bool, error)

BrainVaultClaims returns the edges a vault claims, each with whether the edge was there before any vault claimed it (pre).

func BranchAt added in v0.95.0

func BranchAt(dir string) (string, bool)

BranchAt is the branch checked out in the git checkout holding dir, read from its HEAD file — no git process — and ok=false when there is no checkout, HEAD cannot be read, or it is detached.

It exists because Claude Code's own `gitBranch` cannot be trusted for the main thread: with a background agent working in a linked worktree, the parent's transcript lines kept their cwd and reported the worktree's branch, and the owner's session on master read `feat/cockpit-scrub` (2026-10-09, 0.94.2). A linked worktree has its own HEAD, under the `gitdir:` its `.git` file names.

func CheckSchema added in v0.142.0

func CheckSchema(ctx context.Context, path string) error

CheckSchema reads meta.schema_version from the database at path without the ability to write it, and returns a *SchemaTooNewError when the database is newer than this binary. A missing file, or a database with no meta table yet, is version 0 and passes. Open runs it before it sets a single pragma, so a refused database is left byte for byte as it was found.

Any other failure (a file that is not a database, a lock that outlasts the busy timeout) is returned as is.

func CheckoutOf added in v0.116.0

func CheckoutOf(cwd string) string

CheckoutOf is the folder of the git checkout holding cwd (its nearest `.git` entry, a directory or a linked worktree's file), normalized; a folder in no repository is its own checkout. "" for an empty cwd.

func ClaimBrainEdges added in v0.135.0

func ClaimBrainEdges(ctx context.Context, q Querier, vaultID int64, claims []BrainClaim, now int64) error

ClaimBrainEdges records that a vault wants these edges and makes the ones that are not there. An edge that was there before any vault claimed it is marked pre, so no vault's removal ever takes it away. A claim does not add to an edge's weight, so refreshing a vault does not strengthen its links.

func ClaudeTokensSince added in v0.148.0

func ClaudeTokensSince(ctx context.Context, q Querier, since int64) (int64, error)

ClaudeTokensSince sums the tokens of Claude Code's assistant turns since a moment — input, output, cache read and cache write, the way a read's tokens are counted — in the sessions Caprock recorded. A fork's copy of a turn carries none (rollup zeroes it), and Second Brain's own reads are not sessions (no transcript, no hooks), so they are not in it.

func CleanBrainVaultEntities added in v0.135.0

func CleanBrainVaultEntities(ctx context.Context, q Querier, vaultID int64) error

CleanBrainVaultEntities settles the topics, people and projects a vault's import made: one no edge reaches any more goes, unless it was pinned; one still in use stays and passes to another vault whose edges reach it, or to nobody.

func CleanRepoPaths added in v0.111.0

func CleanRepoPaths(paths []string) []string

CleanRepoPaths normalises paths, drops empties and duplicates, and sorts them: the form project_repos keeps.

func ClearAncestors added in v0.146.0

func ClearAncestors(ctx context.Context, q Querier, id string) ([]string, error)

ClearAncestors returns the sessions id continues in the same process, the nearest first: its parent while the parent ran on the same pid, then that one's, and so on. A fork's parent (another process) ends the walk.

func ClearPendingPermission added in v0.73.0

func ClearPendingPermission(ctx context.Context, q Querier, sessionID string) error

ClearPendingPermission forgets every prompt a session waited on.

func ClearQueued added in v0.104.0

func ClearQueued(ctx context.Context, q Querier, sessionID string) (int64, error)

ClearQueued empties a session's queue and says how many it dropped.

func ClearSuccessor added in v0.146.0

func ClearSuccessor(ctx context.Context, q Querier, id string) (string, error)

ClearSuccessor returns the newest session that continues id in the same process, following /clear after /clear, or "" when none does.

func ClipRunes added in v0.117.1

func ClipRunes(s string, n int) string

ClipRunes shortens s to at most n runes, ending with an ellipsis when cut, after trimming the spaces around it.

func ClipSentence added in v0.125.0

func ClipSentence(s string, n int) string

ClipSentence cuts to n runes at a sentence boundary where one is near the end, so a passage does not stop mid-word (relay.Clip is this).

func CloseTaskAssignments added in v0.12.0

func CloseTaskAssignments(ctx context.Context, q Querier, taskID string, toTs int64) error

CloseTaskAssignments closes every open window on a task at to_ts. Windows are keyed by *session* id (AttributeTaskCost joins events.session_id), and the board — which finishes a task — only knows the hive *agent* id, not the session the router spawned for it. Closing by task is the identifier both sides already agree on, and it is correct when a task was worked by more than one session (a reassignment, or a worker respawned after a crash).

func CountBrainMemories added in v0.117.1

func CountBrainMemories(ctx context.Context, q Querier, manualOnly bool) (int, error)

CountBrainMemories is how many memories (not entities, not imported notes) there are; manualOnly counts those dropped in by hand.

func CountBrainMemoriesSince added in v0.122.0

func CountBrainMemoriesSince(ctx context.Context, q Querier, since int64) (int, error)

CountBrainMemoriesSince counts the memories (not entities, not imported notes) added since a moment, by hand or by a read.

func CountBrainNotes added in v0.135.0

func CountBrainNotes(ctx context.Context, q Querier) (int, error)

CountBrainNotes is how many note nodes there are.

func CountBrainUntagged added in v0.148.0

func CountBrainUntagged(ctx context.Context, q Querier, after int64) (int, error)

CountBrainUntagged counts the memories without keywords above a memory id.

func CountEvents

func CountEvents(ctx context.Context, q Querier) (int64, error)

CountEvents returns the total number of stored events (for status/metrics).

func CountInbox added in v0.115.0

func CountInbox(ctx context.Context, q Querier) (int, error)

CountInbox is how many items there are, for the cap.

func CountSavedPrompts added in v0.102.0

func CountSavedPrompts(ctx context.Context, q Querier) (int, error)

CountSavedPrompts is how many rows there are, for the cap.

func CountSessions added in v0.49.0

func CountSessions(ctx context.Context, q Querier, activeOnly bool) (int, error)

CountSessions returns how many sessions exist under the same filter ListSessions pages through — so a caller can say "200 of 431" rather than presenting a truncated page as the whole set.

func CountSessionsMatching added in v0.59.0

func CountSessionsMatching(ctx context.Context, q Querier, activeOnly bool, search string) (int, error)

CountSessionsMatching counts what ListSessionsMatching would return without a limit.

func CountSessionsQuery added in v0.126.0

func CountSessionsQuery(ctx context.Context, q Querier, f SessionQuery) (int, error)

CountSessionsQuery counts what ListSessionsQuery would return without a limit.

func CountThrottles

func CountThrottles(ctx context.Context, q Querier, sinceMs int64, agent AgentFilter) (int64, error)

CountThrottles counts throttle observations since sinceMs (limit-forecast input). CountThrottles counts rate-limit and overloaded events since sinceMs, through the same agent filter as the figures they are shown beside. The table carries a session id, so the scope is answerable; the empty filter counts every agent.

func DefaultTempDirs added in v0.70.0

func DefaultTempDirs() []string

DefaultTempDirs are the scratch locations on this platform.

func DeleteBrainNode added in v0.117.1

func DeleteBrainNode(ctx context.Context, q Querier, id int64) error

DeleteBrainNode removes a node and its edges. A topic or person the delete leaves with no edge, and that was neither dropped by hand nor pinned, goes too: it existed only to connect what was just deleted.

func DeleteBrainVaultNote added in v0.135.0

func DeleteBrainVaultNote(ctx context.Context, q Querier, id int64) error

DeleteBrainVaultNote removes a note row. The node it marked is not touched; SyncBrainNoteNode settles it.

func DeleteInboxItem added in v0.115.0

func DeleteInboxItem(ctx context.Context, q Querier, id int64) error

DeleteInboxItem removes an item; ErrInboxNotFound when there was none. The caller removes its files.

func DeleteModuleDoc added in v0.131.0

func DeleteModuleDoc(ctx context.Context, q Querier, module, collection, id string) (bool, error)

DeleteModuleDoc removes a document and reports whether there was one.

func DeleteQueued added in v0.104.0

func DeleteQueued(ctx context.Context, q Querier, sessionID string, id int64) error

DeleteQueued takes one message out of a session's queue.

func DeleteSavedPrompt added in v0.102.0

func DeleteSavedPrompt(ctx context.Context, q Querier, id int64) error

DeleteSavedPrompt removes a row; ErrSavedNotFound when there was none.

func DirWithin added in v0.75.0

func DirWithin(dir, root string) bool

DirWithin reports whether dir is root or below it, on segment boundaries. Both are normalised first.

func DisambiguateLabels added in v0.12.2

func DisambiguateLabels(roots map[string]string) map[string]string

DisambiguateLabels resolves collisions among repository labels within one result set: two distinct roots whose basename is the same each grow parent segments until they read differently (`livegraph/repo`, `orch-live/repo`).

This runs over a summary's rows rather than at ingest, because whether a label is ambiguous is a property of the set it is displayed in, not of the repository. A label that is unique — the overwhelming majority — is left exactly as the user would say it.

roots maps each row's label to its repository root; the returned map gives the label to display for each root.

func EachBrainKey added in v0.135.0

func EachBrainKey(ctx context.Context, q Querier, fn func(key string, nodeID int64)) error

EachBrainKey calls fn with every normalised title a node answers to: each memory's own title, and each vault note row's title and aliases (a note node's title is its row's).

func EndSupersededSiblings added in v0.52.1

func EndSupersededSiblings(ctx context.Context, q Querier, pid int, keep string) (int64, error)

func EndedByPID added in v0.116.0

func EndedByPID(ctx context.Context, q Querier, pids []int) (map[int]EndedPID, error)

EndedByPID is, for each pid given, the most recently heard-from ended session that ran in it. The orphan scan asks it about the few claude processes that have no terminal, so the IN list is short.

func EnsureBrainEntity added in v0.117.1

func EnsureBrainEntity(ctx context.Context, q Querier, kind, title string, src BrainSource, manual bool, runID, now int64) (int64, error)

EnsureBrainEntity returns the id of the entity of that kind and title, adding it when there is none.

func EnsureBrainVaultEntity added in v0.135.0

func EnsureBrainVaultEntity(ctx context.Context, q Querier, vaultID int64, kind, title string, now int64) (int64, error)

EnsureBrainVaultEntity returns the entity of a kind and title, adding it, marked as the vault's, when there is none. An existing one is reused whoever made it: a #tag that names a topic Second Brain already has joins that topic.

func EventByKey added in v0.136.0

func EventByKey(ctx context.Context, q Querier, sessionID, key string, kind event.Kind) (event.Event, error)

EventByKey returns the session's event of kind with key: the row a duplicate line was merged into, as it now stands.

func EventsAfter

func EventsAfter(ctx context.Context, q Querier, after int64, limit int) ([]event.Event, error)

Cursor is a stable timeline of events across all sessions (for the live feed catch-up).

func EventsBefore added in v0.40.0

func EventsBefore(ctx context.Context, q Querier, sessionID string, before int64, n int) ([]event.Event, error)

EventsBefore returns the n events immediately preceding `before` (exclusive), oldest-first. before <= 0 means "from the end", which is what LastEvents is.

Paging backwards needs its own query: the timeline used to walk back by asking for the first 1000 events of the session and discarding everything it already had, which on a session with sixteen thousand events fetched the wrong end of the history and threw nearly all of it away.

func EventsVersion added in v0.105.0

func EventsVersion(ctx context.Context, q Querier) (int64, error)

EventsVersion is the newest event's id: it moves on every event written, and an answer counted at one version is still right at the same version unless rows were removed. Read off the primary key, so it costs one lookup.

func FailBrainGap added in v0.148.0

func FailBrainGap(ctx context.Context, q Querier, id int64, msg string, most int, now int64) error

FailBrainGap records a failed read of a gap; after `most` in a row it is given up, its total what it read.

func FinishBrainGap added in v0.148.0

func FinishBrainGap(ctx context.Context, q Querier, id, now int64) error

FinishBrainGap marks a gap read through, its total what it took.

func FirstEventTs added in v0.70.0

func FirstEventTs(ctx context.Context, q Querier) (int64, error)

FirstEventTs is when the first event was recorded (unix ms), or 0 with none: where "all time" starts.

func FirstPrompts added in v0.59.0

func FirstPrompts(ctx context.Context, q Querier, id string, limit int) ([]string, error)

FirstPrompts returns up to limit of a session's earliest user prompts, oldest first. Claude Code carries the text as `prompt`, DeepSeek Harness as `text`.

Pinned to idx_events_user_turn (migration 0033). Left to itself SQLite picked idx_events_kind_ts, which walks every turn.user row in the database and reads each one to test its session: 6ms a session on the owner's 1 GB database, run once per untitled row of /v1/sessions — 330ms of a 50-row list. The partial index holds only user turns, keyed by session and time, with the implicit rowid tail giving (ts, id) order and no sort.

func FirstSessionBySignIn added in v0.159.0

func FirstSessionBySignIn(ctx context.Context, q Querier) (map[string]int64, error)

FirstSessionBySignIn is when each (agent, subscription) first started a session (unix ms), keyed "agent|subscription": how much of a trailing period a sign-in has been recorded for.

func FoldSearch added in v0.120.0

func FoldSearch(s string) string

FoldSearch folds text for matching: compatibility-decomposed (NFKD, so a full-width "A" is "a" and "fi" is "fi"), the combining diacritics of U+0300–U+036F dropped (é is e, ü is u, ά is α), lower-cased by Unicode's rules, and the final sigma made the ordinary one. Other marks stay — a Japanese voicing mark is a different letter, not an accent. The screen's highlighting folds the same way (ui/src/lib/brainsearch.ts).

func GetOffset

func GetOffset(ctx context.Context, q Querier, path string) (int64, error)

Offset persistence for the transcript tailer.

func HandoffCoverage added in v0.51.0

func HandoffCoverage(ctx context.Context, q Querier, since int64, minLen int) (repos int, oldest int64, err error)

HandoffCoverage counts the repositories that hold a passage recent and long enough to hand a new session, and dates the oldest of them.

For the status screen. A feature that acts before anyone types is one nobody can see working — this is how a person checks that it can, without opening a session to find out.

Both figures stop at the first passage that answers them. Counted as one COUNT(DISTINCT) over every passage of the fortnight, the statement parsed the payload of every assistant turn in it — 16,187 page reads (66 MB) of the owner's 1.85 GB database, once a minute while the dashboard polled status, and past its 2 s budget on a swapping machine, which left the figure empty (F17, docs/resource-usage-audit-2026-10-18.md). Now a project counts once one of its sessions holds one passage long enough, found session by session on idx_events_attr_work, and the oldest is the first such passage in time order: 416 page reads, the same two numbers.

func IncForcedContinue

func IncForcedContinue(ctx context.Context, q Querier, sessionID, taskID string) (int, error)

IncForcedContinue bumps and returns the forced-continue count for (session, task).

func InheritOwned added in v0.146.0

func InheritOwned(ctx context.Context, q Querier, id, prev string) error

InheritOwned makes the session a /clear started in a process Caprock started Caprock's as well: owned, with the spawn's worktree, command, sign-in and chat mark. It is the same process, so typing into it is typing into what Caprock started (rule 7). Nothing changes when prev is not owned.

func InsertAttempt added in v0.102.0

func InsertAttempt(ctx context.Context, q Querier, a Attempt) error

InsertAttempt records that a session is attempt n of total in a group.

func InsertBrainNoteNode added in v0.135.0

func InsertBrainNoteNode(ctx context.Context, q Querier, vaultID int64, n BrainVaultNote, now int64) (int64, error)

InsertBrainNoteNode adds the node of a note with no node to join: kind note, made by the vault, under its project, its aliases in its search — what SyncBrainNoteNode would make of it, so a new node needs no sync.

func InsertBrainRun added in v0.117.2

func InsertBrainRun(ctx context.Context, q Querier, r BrainRun) (int64, error)

InsertBrainRun records a read and returns its id.

func InsertBrainVaultNote added in v0.135.0

func InsertBrainVaultNote(ctx context.Context, q Querier, n BrainVaultNote) (int64, error)

InsertBrainVaultNote adds a note row and returns its id.

func InsertEvent

func InsertEvent(ctx context.Context, q Querier, ev *event.Event) (int64, error)

InsertEvent appends an event. Returns ErrDuplicate (and leaves the row alone) when the same (session_id, key) was already stored — the idempotency guarantee that lets ingest re-read a transcript after restart.

func IsBrainEdgeKind added in v0.117.1

func IsBrainEdgeKind(k string) bool

IsBrainEdgeKind reports whether k is an edge kind.

func IsBrainEntity added in v0.117.1

func IsBrainEntity(k string) bool

IsBrainEntity reports whether a kind is an entity — one per normalized title — rather than a memory.

func IsBrainKind added in v0.117.1

func IsBrainKind(k string) bool

IsBrainKind reports whether k is a node kind.

func IsBusy added in v0.70.0

func IsBusy(err error) bool

IsBusy reports whether err is SQLite saying the database was locked by another connection — a write that would succeed if tried again, as opposed to one that is wrong. Callers that would otherwise drop the record they were writing use it to keep it for a later attempt instead.

func IsRemoved added in v0.73.0

func IsRemoved(ctx context.Context, q Querier, sessionID string) (bool, error)

IsRemoved reports whether the owner removed this session (migration 0040).

func LastEvents

func LastEvents(ctx context.Context, q Querier, sessionID string, n int) ([]event.Event, error)

LastEvents returns the newest n events for a session, oldest first.

func LastEventsFiltered added in v0.92.0

func LastEventsFiltered(ctx context.Context, q Querier, sessionID string, n int, f EventFilter) ([]event.Event, error)

LastEventsFiltered is LastEvents with a filter applied before the limit: the n newest events that pass it, oldest first.

func LastMainTurn added in v0.65.0

func LastMainTurn(ctx context.Context, q Querier, sessionID string) (ev event.Event, found bool, err error)

LastMainTurn returns the newest turn.assistant of a session's main thread that carried usage, among its newest mainTurnScan events. found is false when there is none — a session whose every turn is a subagent's, such as an OpenCode child session, or one that has not answered yet.

It exists for the context-fill badge: a subagent starts with a fresh, small prompt, so measuring the session by its subagent's last turn showed an almost full context as almost empty.

func LastPermissionMode added in v0.78.2

func LastPermissionMode(ctx context.Context, q Querier, sessionID string) (string, error)

LastPermissionMode is the permission mode a session was last running in, as Claude Code's own hook payloads state it (`permission_mode`, common to every hook event), or "" when no stored hook carries one — a session observed from its transcript alone, or an agent without hooks.

It reads the stored payloads rather than a column, because every hook payload is already stored verbatim and the mode changes mid-session (⇧Tab cycles it), so the newest event is the answer and a column would be one more thing to keep in step. PostToolUse is skipped: its payload carries the tool's whole output, and it states the same mode as the PreToolUse before it. The value is Claude Code's word for the mode, unvalidated; the caller decides which words it passes on.

func LatestPRByDir added in v0.70.0

func LatestPRByDir(ctx context.Context, q Querier) (map[string]SessionPR, error)

LatestPRByDir is the most recent pull request of any session whose repository (or, outside one, directory) is each of the given keys — the directory a Projects row is keyed on.

func LatestSchema added in v0.142.0

func LatestSchema() (int, error)

LatestSchema is the highest migration number embedded in this binary.

func LinkBrain added in v0.117.1

func LinkBrain(ctx context.Context, q Querier, from, to int64, kind string, weight float64, now int64) error

LinkBrain adds an edge, or strengthens one that exists by adding weight to it, up to BrainEdgeWeightMax. A self-link is ignored.

func LinkToolCall added in v0.71.0

func LinkToolCall(ctx context.Context, q Querier, sessionID, key, msgID string) (bool, error)

LinkToolCall writes the message id onto a stored tool call that has none.

The same call usually reaches the store twice: from the PreToolUse hook, which knows no message id, and moments later from the transcript, which does. Both carry the key `pre:<tool_use_id>`, so the first write wins and the transcript's copy is a duplicate — and with hooks installed the hook is first nearly every time. Without this, the transcript's message id was dropped with the duplicate and the call was never attached to the turn that paid for it: on the owner's database every hook-plane call stored after the one-time backfill of 2026-08-23 had no msg_id (25,924 rows by 2026-10-04).

Only a NULL msg_id is filled: a tool_use id belongs to exactly one message, so an existing link is already right. Returns whether a row changed.

func ListEvents

func ListEvents(ctx context.Context, q Querier, sessionID string, after int64, limit int) ([]event.Event, error)

ListEvents returns events for a session with id > after, oldest first.

func LiveSubagents added in v0.70.0

func LiveSubagents(ctx context.Context, q Querier, sessionID string, since int64) (int, error)

LiveSubagents counts the subagents working in a session now: each agent id heard from since `since` whose latest event is not its SubagentStop.

Claude Code sends no event when a subagent starts, only hooks from inside it (they carry its agent_id) and a SubagentStop when it finishes. So a subagent is live from its first event until its stop, and `since` bounds how long a silent one is believed: one whose stop never arrived must not count forever.

func MarkBrainAutomation added in v0.157.0

func MarkBrainAutomation(ctx context.Context, q Querier, sessionID string, now int64) error

MarkBrainAutomation records, at a session's spawn, that Second Brain is never to read it (BrainSkipAutomation): a skipped run with no span. A second mark on the same session is not written twice.

func MarkBrainRootOrHome added in v0.158.0

func MarkBrainRootOrHome(ctx context.Context, q Querier, c BrainCandidate, now int64) error

MarkBrainRootOrHome records that a session started at a root or in the home directory itself is never read (BrainSkipRootOrHome, with its cwd): a skipped run through the session's newest event, so nothing of it waits.

func MarkChat added in v0.126.0

func MarkChat(ctx context.Context, q Querier, id string) error

MarkChat records that a session is a chat. Idempotent.

func MarkDailySession added in v0.49.1

func MarkDailySession(ctx context.Context, q Querier, day, project, sessionID string) (bool, error)

MarkDailySession records that a session was seen on a day, and reports whether this was the first time.

The caller used to answer "is this a new session" with "is this its first turn ever", so a session that started yesterday added nothing to today — four of eight days on the owner's database read zero sessions beside real spend.

Keyed by day and project, deliberately not by model. daily_stats *is* keyed by model and the dashboard sums a day's rows, so the count has to live in exactly one place: keyed by model as well, a session that switched from Opus to Haiku mid-day would be counted twice, which measured as 3 against a true 2 on 27 August.

func MarkEndedSessions

func MarkEndedSessions(ctx context.Context, q Querier, before int64) ([]string, error)

MarkEndedSessions ends sessions whose process is gone, and — only for sessions whose process was never known — sessions silent since `before`.

A session is over when its process exits, not when it goes quiet. Every number picked for "quiet enough" was wrong for somebody: twelve hours left the day's work marked live at midnight, one hour closed a session while its owner was at lunch. Both are guesses about a person's day standing in for a fact about a process, and the fact is available — the shim reports the pid of the Claude Code that ran it, and Caprock records the pid of every session it spawns itself.

So a session with a pid is judged only by whether that pid is alive, and may sit quiet for a week without being touched. `before` applies solely to sessions with no pid: rows written by an older shim, or read from a transcript with no live process behind them, where there is nothing to ask and a backstop is all there is.

One fact is still available for those: the disk. A watched session with no pid whose transcript file is gone, or whose directory is gone, ends now rather than a day from now (see goneFromDisk). Imported history (OpenCode, Codex, DeepSeek, Hermes) stays on the clock alone.

func MarkIdleEnded added in v0.143.0

func MarkIdleEnded(ctx context.Context, q Querier, id string, at, after int64) error

MarkIdleEnded records that Caprock is ending a session because it sat idle with no tab for after (ms), at at (unix ms); 0, 0 takes it back (the end could not be asked for).

func MarkIdleSessions

func MarkIdleSessions(ctx context.Context, q Querier, before int64) ([]string, error)

MarkIdleSessions flips active sessions with no event since `before` (unix ms) to idle. Returns the ids that changed.

func MarkOwned

func MarkOwned(ctx context.Context, q Querier, id, worktree, spawnCommand string, pid int) error

MarkOwned records that Caprock spawned this session (Phase 1).

func MeasureBrainGap added in v0.148.0

func MeasureBrainGap(ctx context.Context, q Querier, id, to int64, reads int, now int64) error

MeasureBrainGap records a gap's last event and how many reads it takes; a gap where nothing was skipped (to or reads 0) is deleted instead.

func MergeAssistantText added in v0.70.0

func MergeAssistantText(ctx context.Context, q Querier, sessionID, key string, payload json.RawMessage) (bool, error)

MergeAssistantText folds the prose and tool names of a later line of one API response into the turn row that response is stored as.

Claude Code writes one response as several transcript lines — thinking, then text, then each tool_use — every one carrying the same message id and usage. The store keys turns on `msg:<id>` so usage is counted once, which keeps the FIRST line and dropped the rest. While the first line was usually the text that did not matter; once Claude Code began writing a thinking line first on every response, the stored turn kept an empty `text` and the prose that followed it never reached the database. On the owner's machine 93% of the assistant turns stored after 2026-09-29 had no text, against 10-28% in every earlier week (measured 2026-10-04), and the Answers tab of a session full of long replies showed one line.

Only the payload changes: usage, cost and id stay as the first line set them. It is idempotent — a transcript re-read after a restart offers the same lines again, and text already in the row is not appended twice. Returns whether the row changed.

func MovedOnSince added in v0.73.0

func MovedOnSince(ctx context.Context, q Querier, sessionID string, sinceMs int64) (bool, error)

MovedOnSince reports whether a session recorded anything after sinceMs that means a permission dialog drawn then is no longer on screen: a tool finishing, a prompt or reply, a turn ending, or the session ending. Another permission.prompt does not count: Claude Code queues dialogs, so a later one leaves the earlier on screen.

func NormTitle added in v0.117.1

func NormTitle(s string) string

NormTitle folds a title for comparison: lower case, punctuation at the ends dropped, runs of spaces made one. "SQLite " and "sqlite." are one topic.

func NormalizeDir added in v0.75.0

func NormalizeDir(dir string) string

NormalizeDir puts a directory into the one form the store keeps paths in: forward slashes, no trailing separator (sessions.repo_root, projects.root).

func NotAProject added in v0.72.0

func NotAProject(cwd string) bool

NotAProject reports whether cwd is a place nobody works in as a project: a filesystem root, the home directory itself, or a temp directory itself.

Sessions do start there — on the owner's Mac a background `claude` opens in "/" every ten minutes and exits seconds later — but such a directory is no project to offer in the New session picker, and no repository whose last passage a new session should be handed. Subdirectories are unaffected.

func OpenAssignment

func OpenAssignment(ctx context.Context, q Querier, taskID, sessionID string, fromTs int64) error

OpenAssignment records that a session started working a task at from_ts. It is a no-op when an open window already exists for that (task, session), so a caller may invoke it every tick without stacking duplicate windows.

func Overlaps added in v0.116.0

func Overlaps(ctx context.Context, q Querier, live []Session, sinceMs int64) (map[string]SessionOverlap, error)

Overlaps groups the live sessions by checkout and, for every group of two or more, reads which files each edited since sinceMs: one query on session_files (Edit, Write, MultiEdit and NotebookEdit paths, kept by the rollup with their last edit), only for the sessions in a shared checkout. A session alone in its checkout is absent from the answer, so the usual case — nobody shares — asks the database nothing beyond the session list.

func PRToolPosts added in v0.70.0

func PRToolPosts(ctx context.Context, q Querier, fn func(sessionID string, ts int64, payload []byte) error) error

PRToolPosts streams the Bash PostToolUse rows that recorded a `gh pr` operation or ran `gh pr create`, for the one-off history backfill. A LIKE on the payload: this runs once, after the port opens.

func PRURLPrefix added in v0.153.0

func PRURLPrefix(repo string) string

PRURLPrefix is the address every pull request of repo ("owner/name") starts with on github.com.

func PreviousOnPID added in v0.60.0

func PreviousOnPID(ctx context.Context, q Querier, pid int, id string) (string, error)

updateStatusByID sets one status on a known set of sessions, in chunks that stay well inside SQLite's variable limit. EndSupersededSiblings retires the other sessions running under `pid`, leaving `keep` alone. It exists for /clear, which starts a fresh session id inside a process that is already running one.

The staleness sweep cannot do this. It judges a session by whether its process is alive (ADR-028), and after a /clear the old session's process is not merely alive — it is the very process now serving the new session. So the old row stayed `active` forever, and the dashboard showed one Claude Code as two live sessions, one of them frozen at the moment it was cleared, its six-day cost and 95%-full context still presented as current.

A process runs exactly one Claude Code conversation at a time, so a sibling on the same pid is finished by definition. pid 0 means "unknown" and is never matched: it would sweep together every session whose pid was never recorded. PreviousOnPID is the session that most recently started in the same process before id — the one a /clear replaced. Empty when there is none.

func ProcessAlive added in v0.45.0

func ProcessAlive(pid int) bool

ProcessAlive reports whether a process is still running.

This is what replaced a timer. Caprock used to decide a session was over because it had been quiet for a while, and every number chosen for "a while" was wrong for somebody: twelve hours left the day's sessions live at midnight, and one hour closed a session while its owner was at lunch. A session is over when its process is gone, which is a fact rather than a guess, and the only reason the staleness sweep still exists at all is sessions whose pid was never learned.

On unix, signal 0 is the "does this pid exist and may I signal it" test: it performs the permission and existence checks and delivers nothing. A pid belonging to another user answers EPERM, which is still proof the process is there — Caprock is single-user, but a session left by `sudo` should not be declared dead because of a permission error.

The known unsoundness is pid reuse: a dead process's number can be handed to a new one, and this would call that session alive. Detecting it means comparing process start times, which is three platforms of code for a case that requires a wrap of the pid space between two sweeps. The failure it would prevent is a stale row in a list; the failure of not doing this at all was a session vanishing while somebody worked in it.

A reboot is the exception, because it resets the pid space and makes reuse the common case rather than a wrap: MarkEndedSessions checks BootTime first.

func ProjectActivityByDir added in v0.75.0

func ProjectActivityByDir(ctx context.Context, q Querier, sinceMs int64) (map[string]*ProjectActivity, error)

ProjectActivityByDir aggregates sessions and today's spend by directory key (the repository root, else the cwd), the same key RecentDirs groups by. The caller attributes each key to the project that contains it.

Live is a session not ended; waiting is a live one whose newest event is a permission prompt, a main-thread StopFailure, or a main-thread Stop whose last message asks something with no subagent still working (LiveSubagents) — what narrate calls waiting-on-you. A Stop that asks nothing is Done and is not counted (§ Needs you and Done). Spend is events at or after sinceMs, internal ones left out as every total leaves them out.

func ProjectFromCwd

func ProjectFromCwd(cwd string) string

ProjectFromCwd derives the project label for a working directory: the repository it belongs to, not the basename of the directory.

This is the ingest-time label written to sessions.project, so a session in caprock/ui is `caprock`. Kept as the same name and signature the callers already use.

func ProjectRepos added in v0.111.0

func ProjectRepos(ctx context.Context, q Querier) (map[int64][]string, error)

ProjectRepos lists the member repositories of every multi-repo project (migration 0050, ADR-055), keyed by project id, each list sorted by path.

func ProjectWorthListing added in v0.75.0

func ProjectWorthListing(root string) bool

ProjectWorthListing reports whether a repository root found from sessions should be on the projects list without anyone adding it: still on disk with a `.git` directory of its own (not a linked worktree, not a Caprock agent worktree), and not a place nobody works in (NotAProject) or a temp directory's scratch repository.

func PromptTexts added in v0.110.0

func PromptTexts(ctx context.Context, q Querier, ids []int64, limit int) (map[int64]string, error)

PromptTexts returns the prompt of each turn.user event by id, as typed (payload.prompt, else payload.text), clipped to limit runes.

func ProseSince added in v0.52.0

func ProseSince(ctx context.Context, q Querier) (int64, error)

ProseSince is when the oldest passage Caprock still holds was written.

Distinct from HandoffCoverage's date, which is bounded by how far back a handoff will reach (a fortnight). The search screen spans everything, and showing the shorter date there would understate the corpus by a month.

func PruneEventsBefore

func PruneEventsBefore(ctx context.Context, q Querier, beforeMs int64) (int64, error)

PruneEventsBefore deletes events older than beforeMs, keeping session rows and their rollups (session_stats/daily_stats stay — the totals are already materialized). Returns the number of events removed. This is the data-growth safety valve; it never touches sessions the user might still be looking at (callers pass a cutoff well in the past).

func PrunePendingPermissions added in v0.73.0

func PrunePendingPermissions(ctx context.Context, q Querier, keep map[string]bool) error

PrunePendingPermissions deletes every stored prompt whose session is not in keep: a session that ended while no daemon was running is waiting on nothing.

func PutEventTLDR added in v0.128.0

func PutEventTLDR(ctx context.Context, q Querier, t EventTLDR) error

PutEventTLDR keeps a squeeze, replacing one already kept for the event.

func QueuedSessions added in v0.104.0

func QueuedSessions(ctx context.Context, q Querier) ([]string, error)

QueuedSessions returns every session that has a message waiting.

func RateLimitHistoryMark added in v0.141.0

func RateLimitHistoryMark(ctx context.Context, q Querier, window string) (int64, error)

RateLimitHistoryMark is the newest history sample's time for a window, 0 when there is none: one lookup on idx_rate_limit_history_window_ts. Samples are only ever appended later than the newest (RecordRateLimit), so while the mark has not moved RateLimitPace has not either.

func RateLimitPace added in v0.4.0

func RateLimitPace(ctx context.Context, q Querier, window string, resetsAt int64) (pctPerHour float64, ok bool, err error)

RateLimitPace returns the observed usage slope (percentage points per hour) for a window's CURRENT reset cycle. ok is false unless there are ≥2 same-window (same resets_at) history samples spanning ≥60s with a strictly rising usage — the honesty gate for the "at current pace" forecast. It never extrapolates across a reset boundary and never reports a flat/declining slope.

func RecentOwnedSessions added in v0.110.0

func RecentOwnedSessions(ctx context.Context, q Querier, since time.Time) ([]string, error)

RecentOwnedSessions returns the sessions Caprock started that recorded anything at or after since.

func RecordBrainVaultScan added in v0.135.0

func RecordBrainVaultScan(ctx context.Context, q Querier, id int64, notes int, scanMs int64, errText string, now int64) error

RecordBrainVaultScan keeps how a scan went: the notes it found, how long it took and why it failed ("" when it did not).

func RecordExit added in v0.157.0

func RecordExit(ctx context.Context, q Querier, e SessionExit) error

RecordExit stores how an owned session ended; a later exit under the same id (a permission-mode restart, a resume under its own id) replaces it.

func RecordPR added in v0.70.0

func RecordPR(ctx context.Context, q Querier, a PRAction) error

RecordPR folds one `gh pr` command into session_prs. Only created, merged and closed are recorded; an edit or a comment is not a PR the session opened. An action that came without a URL is matched by number within the session, and dropped when the session has no such PR. Idempotent: replaying the same action leaves the row as it was.

func RecordRateLimit added in v0.4.0

func RecordRateLimit(ctx context.Context, q Querier, s RateLimitSnapshot, sessionID string) error

RecordRateLimit upserts the latest state for a window and, throttled, appends a history row for the "at current pace" slope. The latest row is always current; history rows are sampled (≥30s apart) to avoid write amplification.

func RecordThrottle

func RecordThrottle(ctx context.Context, q Querier, ts int64, sessionID, kind string, payload []byte) error

RecordThrottle appends a throttle observation (Phase 1: capture now, model later).

func RecordVerification

func RecordVerification(ctx context.Context, q Querier, taskID string, round int, command string, exitCode int, outputPath string) error

RecordVerification stores one verification-command result.

func RefreshToolFields added in v0.151.0

func RefreshToolFields(ctx context.Context, q Querier, id int64) error

RefreshToolFields re-reads one event's fields after its payload was rewritten in place (a Codex call whose input was repaired).

func RelayLinks(ctx context.Context, q Querier, sess Session) (*RelayLink, []RelayLink, error)

RelayLinks returns the session this one was relayed from (nil when none or unknown) and the sessions relayed from it, oldest first.

func ReleaseBrainEdges added in v0.135.0

func ReleaseBrainEdges(ctx context.Context, q Querier, vaultID int64, claims map[BrainClaim]bool) error

ReleaseBrainEdges drops a vault's claims on these edges, and each edge itself when no other vault claims it and no vault found it already there.

func ReleaseOwned added in v0.70.1

func ReleaseOwned(ctx context.Context, q Querier, id string) error

ReleaseOwned records that a session is no longer Caprock's: its process was stopped so the user could carry it on in their own terminal. Without this, the resumed session would read as one Caprock started and then lost the terminal of.

func RemoveBrainVault added in v0.135.0

func RemoveBrainVault(ctx context.Context, q Querier, id int64, now int64) error

RemoveBrainVault takes a vault out of Second Brain: its claims on edges (and the edges no one else wants), its note rows, the note nodes no other source keeps, the entities only it used, and the vault. Nodes it only added a source to stay as they were. Set-based: a 5,000-note vault is a handful of statements, not one per edge.

func RemoveSession added in v0.73.0

func RemoveSession(ctx context.Context, q Querier, c RemovalCandidate, loc *time.Location, nowMs int64) (float64, error)

RemoveSession deletes a session, its events and everything built from them, and records it in removed_sessions so the recorder never stores it again (ADR-037). Run it inside one transaction.

daily_stats is shared with every other session of the same day, project and model, so the session's turns are taken back out of it rather than the rows deleted — the inverse of what rollup.Record added, as codex.removeRows does. It returns the cost it could not find a row to take out of, which is zero unless a turn's day row was rebuilt under another project name since.

func ReplacePendingPermissions added in v0.78.2

func ReplacePendingPermissions(ctx context.Context, q Querier, sessionID string, ps []PendingPermission) error

ReplacePendingPermissions makes the stored queue of a session exactly ps, in that order.

func ReplaceRateLimits added in v0.63.0

func ReplaceRateLimits(ctx context.Context, q Querier, prefix string, sessionID string, snaps []RateLimitSnapshot) (bool, error)

ReplaceRateLimits swaps every window under prefix for those in one newer sample, and reports whether it did.

Replaced as a set rather than upserted per window, because a sample that omits a window is a statement about the plan: on the owner's machine a Codex account moved from `plus` (5-hour and weekly windows) to `prolite` (weekly only), and an upsert would have kept showing the five-hour figure from the old plan forever. A sample no newer than the stored one is ignored — transcripts are imported newest-modified first and out of order, and the latest observation is the only one shown.

Like RecordRateLimit it also appends each window to rate_limit_history, throttled the same way (one row per window per 30 s), so the plan figures can calibrate a Codex week once it has ended (internal/planshare). No forecast is built on those rows: the Codex windows are shown as last observed. Run it in a transaction.

func RepoPathFromCwd added in v0.12.2

func RepoPathFromCwd(cwd string) string

RepoPathFromCwd returns the path within the repository for a cwd — the second level of the grouping, stored so the breakdown needs no filesystem access on read.

func RepoRootsKey added in v0.122.0

func RepoRootsKey(roots []string) string

RepoRootsKey is roots as one cache key: sorted, so the order a client sends them in does not split the cache.

func ResetForcedContinue

func ResetForcedContinue(ctx context.Context, q Querier, sessionID, taskID string) error

ResetForcedContinue clears the counter (task moved on).

func ResolveRepoRoot added in v0.75.0

func ResolveRepoRoot(dir string) string

ResolveRepoRoot is the repository root dir belongs to, read from disk now rather than from RepoFromCwd's memo (which keeps a folder's answer for the daemon's life, so a `git init` after the first look would be missed), or "" when dir is in no repository.

func RootOrHome added in v0.158.0

func RootOrHome(cwd string) bool

RootOrHome reports whether cwd is a filesystem or drive root ("/", `C:\`) or the user's home directory itself (%USERPROFILE% on Windows) — not a folder under it, and not "" (a session with no recorded cwd). Second Brain never reads a session started there: a scheduled `claude -p` run by launchd or cron opens in "/", and nobody keeps a project in either (owner, 2026-10-24). It is NotAProject without the temp directories.

func RunningAt added in v0.60.0

func RunningAt(ctx context.Context, q Querier, stoppedAt int64, limit int) ([]string, error)

RunningAt lists the sessions that look as if they were running at stoppedAt, when the daemon last stopped: not ended yet, or ended by that very stop — a close recorded within a couple of minutes of it. Only sessions somebody worked in on the day of the stop count, and only agents whose process Caprock watches, so imported history and long-abandoned rows stay out. Newest work first, at most limit.

func SavePendingPermission added in v0.73.0

func SavePendingPermission(ctx context.Context, q Querier, p PendingPermission) error

SavePendingPermission records one more prompt a session waits on, behind the ones already stored: Claude Code queues its dialogs and shows the oldest. Saving a prompt id again updates its row in place.

func ScrubBrainSecrets added in v0.150.0

func ScrubBrainSecrets(ctx context.Context, q Querier, now int64) (nodes, notes int, counts redact.Counts, err error)

ScrubBrainSecrets redacts, in place, every node's title, summary and keywords and every imported note's excerpt that holds a value the filter finds, rebuilding the search document of each node it changes. It returns how many nodes and note rows changed and the values replaced, by kind. It is idempotent: a second run finds nothing. An entity whose redacted title would collide with another of its kind keeps its title.

func SeedProject added in v0.75.0

func SeedProject(ctx context.Context, q Querier, p Project) (bool, error)

SeedProject adds a project found from sessions, unless its root is already a row — listed or unlisted, so an unlisted project stays off the list. Reports whether a row was added.

func SessionFiles

func SessionFiles(ctx context.Context, q Querier, sessionID string, limit int) ([]string, error)

SessionFiles lists paths a session touched, most recent first.

func SessionForNative added in v0.70.0

func SessionForNative(ctx context.Context, q Querier, agent, nativeID string) (string, error)

SessionForNative returns the Caprock session linked to an agent's own id, or "" when none is.

func SessionProject added in v0.117.1

func SessionProject(ctx context.Context, q Querier, sessionID string) (string, error)

SessionProject returns a session's project, ” when unknown.

func SessionRanIn added in v0.113.0

func SessionRanIn(ctx context.Context, q Querier, dir string) (bool, error)

SessionRanIn reports whether any recorded session ran in dir. The data directory's sweep asks it before removing an empty chat directory, which a resumed chat would start in again.

func SetAttemptTotal added in v0.102.0

func SetAttemptTotal(ctx context.Context, q Querier, group string, total int) error

SetAttemptTotal says how many of a group started, when fewer did than asked.

func SetBrainKeywords added in v0.148.0

func SetBrainKeywords(ctx context.Context, q Querier, id int64, keywords []string) (bool, error)

SetBrainKeywords gives a memory that has none its keywords, cleaned as an extraction's are, and writes them into its search document. It reports whether it did: a memory that has keywords by now (a read or another batch got there first), that is not a memory, or that is gone, is left as it is. updated_at does not move: keywords are a search aid, not an edit.

func SetBrainRunNodes added in v0.117.2

func SetBrainRunNodes(ctx context.Context, q Querier, id int64, nodes int) error

SetBrainRunNodes records how many nodes a read made, once they are stored.

func SetBrainVaultAgents added in v0.135.0

func SetBrainVaultAgents(ctx context.Context, q Querier, id int64, on bool) error

SetBrainVaultAgents turns a vault's notes reaching agents on or off.

func SetChatArchived added in v0.126.0

func SetChatArchived(ctx context.Context, q Querier, id string, at int64) error

SetChatArchived archives a chat at `at` (unix ms), or brings it back when at is 0. sql.ErrNoRows when id is not a chat: a work session is not archived from the Chats list.

func SetExit

func SetExit(ctx context.Context, q Querier, id string, code int) error

SetExit records an owned session's exit code and marks it ended.

func SetHandoff added in v0.61.0

func SetHandoff(ctx context.Context, q Querier, id string, state int) error

SetHandoff records what a new session was given when it opened.

func SetHandoffBrain added in v0.122.0

func SetHandoffBrain(ctx context.Context, q Querier, sessionID string, n int) error

SetHandoffBrain records how many Second Brain memories a new session was handed with its handoff (migration 0058).

func SetHandoffRunes added in v0.148.0

func SetHandoffRunes(ctx context.Context, q Querier, sessionID string, n int) error

SetHandoffRunes records how long a new session's handoff was, in runes of its additionalContext (migration 0069).

func SetName added in v0.115.0

func SetName(ctx context.Context, q Querier, id, name string) (ok bool, err error)

SetName records the user's own name for a session; an empty name clears it, and the agent's title or first prompt names the session again. Unlike SetTitle this is the user's word, so empty is a value, not a no-op. ok is false when no such session is stored.

func SetNativeID added in v0.70.0

func SetNativeID(ctx context.Context, q Querier, id, nativeID string) (bool, error)

SetNativeID links a session Caprock started to the agent's own id for it (migration 0032). Written once: a link already made is never moved to a different thread, because the events stored under it came from the first. Reports whether the link was made.

func SetOffset

func SetOffset(ctx context.Context, q Querier, path, sessionID string, off int64) error

func SetParent added in v0.60.0

func SetParent(ctx context.Context, q Querier, id, parent string) error

SetParent records the session id continues. It never replaces one already known.

func SetProjectGit added in v0.75.0

func SetProjectGit(ctx context.Context, q Querier, id int64, remoteURL, defaultBranch string) error

SetProjectGit records what git says a project's remote and default branch are, when they changed.

func SetProjectRepos added in v0.111.0

func SetProjectRepos(ctx context.Context, q Querier, id int64, paths []string, at int64) ([]string, error)

SetProjectRepos replaces project id's member repositories with paths (CleanRepoPaths). A repository is a member of one project at a time: a path another project held moves here. An empty list makes the project an ordinary one again. Nothing on disk is touched. Run it inside a transaction (Store.WithTx) so a move is never half done.

func SetPrompt added in v0.59.0

func SetPrompt(ctx context.Context, q Querier, id, prompt string) error

SetPrompt records the first thing the user typed, for an agent whose prompts are not events. Same rules as SetTitle: empty is a no-op, a missing session is not created.

func SetRelayFrom added in v0.70.0

func SetRelayFrom(ctx context.Context, q Querier, id, from string) error

SetRelayFrom records that a session was started to carry on another's work (migration 0036).

func SetSessionStatus

func SetSessionStatus(ctx context.Context, q Querier, id, status string) error

SetSessionStatus forces a status (idle/ended/active).

func SetSubagentModel added in v0.138.0

func SetSubagentModel(ctx context.Context, q Querier, id, model string) error

SetSubagentModel records the model a session's subagents were started on.

func SetTitle added in v0.59.0

func SetTitle(ctx context.Context, q Querier, id, title string) error

SetTitle records the agent's own name for a session. An empty title is a no-op, so a line that names nothing cannot erase a name already known; a session that does not exist yet is left alone rather than created.

func SpendByBranch added in v0.111.0

func SpendByBranch(ctx context.Context, q Querier, repoRoot string) (map[string]BranchSpend, error)

SpendByBranch sums the sessions of repository repoRoot (sessions.repo_root, as ingest resolved it) per branch, read through idx_sessions_repo_branch (migration 0051). A session with no branch recorded is left out.

func SpendByPR added in v0.116.0

func SpendByPR(ctx context.Context, q Querier, repoRoot string, prs []PRRef) (map[string]PRSpend, error)

SpendByPR charges the sessions of repository repoRoot to the pull requests prs, keyed by URL. Where two of prs share a head branch, the first in prs owns it: pass the open one first, then the newest. Three small reads: the repository's sessions with a branch (through idx_sessions_repo_branch), the session_prs rows of the sessions that worked on one of prs, and, for a session cut between several, one sum per slice over its events (through its (session_id, ts) index).

func SpendBySessionSince added in v0.118.0

func SpendBySessionSince(ctx context.Context, q Querier, ids []string, fromMs int64) (map[string]float64, error)

SpendBySessionSince is each given session's priced cost of events at or after fromMs (internal model work left out, as every user total does). A session with nothing priced since is absent.

One grouped sum over idx_events_attr_work, which leads on (session_id, ts) and carries cost_usd and internal, so no table row is read.

func SpendOn added in v0.159.0

func SpendOn(ctx context.Context, q Querier, agent, subscription string, fromMs, toMs int64) (float64, error)

SpendOn is the priced work of one sign-in in [fromMs, toMs): agent and subscription as sessions record them. The weekly calibration's spend.

func SpendSince added in v0.39.0

func SpendSince(ctx context.Context, q Querier, fromMs int64) (float64, error)

SpendSince is the total priced cost of events at or after fromMs.

The daily spend cap's only question, asked after every priced turn, so it is one indexed sum and nothing else. Unpriced turns contribute nothing: a model missing from the pricing table leaves cost_usd NULL, and COALESCE flattens it — the cap therefore under-counts rather than inventing a figure, which is the safe direction for something that stops work.

func SyncBrainNoteNode added in v0.135.0

func SyncBrainNoteNode(ctx context.Context, q Querier, nodeID int64, now int64) (deleted bool, err error)

SyncBrainNoteNode settles a node after its note rows changed. A note node with no row left is deleted, with its edges. A note node with rows takes its title, summary, project and time from the oldest row — the source that made it — and belongs to that row's vault. Any node with rows has the rows' aliases and the other rows' excerpts in its search, so a search finds it by any of its sources; their texts are never merged into its summary. deleted is true when the node went.

func TimedCalls added in v0.70.0

func TimedCalls(calls []TaxCall) []contexttax.TimedCall

TimedCalls converts calls for contexttax.PriceSeries.

func TouchDir added in v0.14.0

func TouchDir(payload []byte) string

TouchDir extracts the directory a tool call touched from its stored payload.

It returns "" when the tool named no path, which is the common case: on the owner's 65915 tool.pre rows, only Read, Edit, Write and Artifact carry a path at all. That is deliberate — see TouchRule.

func TouchFile

func TouchFile(ctx context.Context, q Querier, sessionID, path string, ts int64) (bool, error)

TouchFile records that a session touched a path. Returns true when the path is new for the session.

func TurnPaidElsewhere added in v0.68.0

func TurnPaidElsewhere(ctx context.Context, q Querier, msgID, sessionID string) (bool, error)

TurnPaidElsewhere reports whether a session other than sessionID already holds an assistant turn for msgID that carries usage.

A message id names one API response, and one response is billed once. Claude Code nevertheless writes the same response into more than one transcript: a fork (`--resume <id> --fork-session`) copies the parent's history since its last compaction into the new session's file, ids and usage included. The store dedupes on (session_id, key), which cannot see that, so the copy was priced a second time.

Only a row with usage counts as the payer. Claude Code zeroes the usage scalars of the first messages it preserves across a compaction, so a copy can arrive with nothing on it — and if that copy happened to be stored first, the original must still be priced when it arrives.

func UnderDir added in v0.157.0

func UnderDir(p, dir string) bool

UnderDir reports whether p is dir itself or lies beneath it, on segment boundaries, both put into the store's form first (NormalizeDir). "" is under nothing and nothing is under "".

func UnderTempDir added in v0.75.0

func UnderTempDir(dir string) bool

UnderTempDir reports whether dir is inside a temp directory: the scratch repositories tests and agents make there are not projects.

func UnlinkBrain added in v0.117.1

func UnlinkBrain(ctx context.Context, q Querier, a, b int64) error

UnlinkBrain removes every edge between two nodes, in either direction.

func UnlinkBrainKind added in v0.148.0

func UnlinkBrainKind(ctx context.Context, q Querier, from, to int64, kind string) error

UnlinkBrainKind removes the one edge of a kind from one node to another, leaving any other edge between them: undoing a wrong supersedes keeps the two memories related.

func UpdateBrainVaultNote added in v0.135.0

func UpdateBrainVaultNote(ctx context.Context, q Querier, n BrainVaultNote) error

UpdateBrainVaultNote rewrites a note row in place (same path, same node).

func UpdateProject added in v0.75.0

func UpdateProject(ctx context.Context, q Querier, id int64, patch ProjectPatch) error

UpdateProject applies patch to project id.

func UpdateQueued added in v0.104.0

func UpdateQueued(ctx context.Context, q Querier, sessionID string, id int64, text string, now time.Time) error

UpdateQueued replaces a waiting message's text, keeping its place.

func UpsertSession

func UpsertSession(ctx context.Context, q Querier, id string, p SessionPatch) error

UpsertSession creates or updates a session from a patch.

func UpsertTask

func UpsertTask(ctx context.Context, q Querier, t TaskRow) error

UpsertTask mirrors a hive task into SQLite.

Types

type AgentFilter added in v0.22.0

type AgentFilter string

AgentFilter restricts a summary to one coding agent. Empty means every agent, which is what every caller wanted before OpenCode existed.

The predicate is a subquery on sessions rather than a join, for two reasons: events carries no agent of its own (it belongs to the session), and a join would change the row multiplicity of five separate aggregate queries — a silent way to double a cost. A subquery leaves each query's shape alone.

type AssistantNote added in v0.9.0

type AssistantNote struct {
	EventID   int64  `json:"event_id"`
	SessionID string `json:"session_id"`
	Project   string `json:"project"`
	Ts        int64  `json:"ts"`
	Model     string `json:"model"`
	Text      string `json:"text"`
	// Fragment marks a note that reads as mid-thought rather than a conclusion
	// ("Let me check that"), so a caller can avoid presenting it as a summary.
	Fragment bool `json:"fragment"`
}

AssistantNote is one thing Claude actually said, in prose — the reasoning and the closing "here is what changed, here is what I still need from you" that people otherwise copy into a notepad or lose to terminal scrollback.

func SearchNotes added in v0.9.0

func SearchNotes(ctx context.Context, q Querier, query string, limit int, before int64) ([]AssistantNote, error)

SearchNotes finds prose across every session — the question people actually ask is "which session was it where Claude explained the SSO thing?", not "show me session 17". An empty query returns the most recent notes. SearchNotes returns Claude's prose, newest first. `before` pages backwards: pass the lowest event_id already shown to get the next page, or 0 to start.

Paging is not an optimisation here, it is the feature working at all. The screen used to load a fixed 500 and stop, which on a busy machine is half a day — one reporter saw an entry from 22 hours ago followed immediately by one from 30 days ago, and reasonably read it as data loss. Nothing was lost; the middle was never fetched.

func SessionNotes added in v0.9.0

func SessionNotes(ctx context.Context, q Querier, sessionID string, limit int) ([]AssistantNote, error)

SessionNotes returns what Claude said in a session, newest first. Sidechains are excluded; the caller gets main-thread prose only.

func WhereWeLeftOff added in v0.51.0

func WhereWeLeftOff(ctx context.Context, q Querier, project string, before int64, minLen int) (AssistantNote, error)

WhereWeLeftOff is the last substantial thing an agent said in a repository, for handing back to the next session that opens there.

The question a person asks on returning is not "find something similar" — it is "what were we doing". Measured on the owner's database: searching prior prose by the terms of the opening prompt found something useful in 4 of 15 resumed sessions, and missed the clearest case of all ("remind me what we were looking into last time", 384 candidate passages, nothing matched) because an opening question shares no words with its own answer. Taking the last substantial passage instead answers 12 of 19. Recency beats retrieval here.

`before` excludes the session now starting, so a session cannot be handed its own output; `minLen` skips one-liners like "Done." that say nothing about where the work stood.

The project is tested on the covering index, before any payload is read. As a join on sessions, every assistant turn in the database had its payload fetched and parsed before the project was checked, so a project with no passage long enough — every session from "/" — walked all of history: 4-6 s on the owner's 1.2 GB database (2026-10-05), longer than the SessionStart hook waits, and the lookup died cancelled every time. The session ids are on idx_events_turn_agent, so rows of other projects are skipped without touching their payloads: under 0.1 s for any project, same answers.

type Attempt added in v0.102.0

type Attempt struct {
	SessionID string `json:"session_id"`
	GroupID   string `json:"group_id"`
	N         int    `json:"n"`
	Total     int    `json:"total"`
	// Base is the branch the copies started from; BaseCommit the commit it
	// pointed at, which each attempt's changes are measured from.
	Base       string `json:"base,omitempty"`
	BaseCommit string `json:"base_commit,omitempty"`
	CreatedAt  int64  `json:"created_at"`
}

Attempt is one of several sessions started on the same first message, each in a new copy of the same branch (migration 0046, ADR-052).

func AttemptGroup added in v0.102.0

func AttemptGroup(ctx context.Context, q Querier, group string) ([]Attempt, error)

AttemptGroup returns a group's attempts in order; empty for an unknown one.

type BackgroundUsage added in v0.57.0

type BackgroundUsage struct {
	Turns  int64    `json:"turns"`
	Tokens int64    `json:"tokens"`
	Models []string `json:"models"`
}

BackgroundUsage is known internal work observed in real transcripts. The raw events remain available, but these calls are not sessions or turns the user started and therefore do not belong in user-work totals.

type BrainAgentRead added in v0.146.0

type BrainAgentRead struct {
	Agent    string `json:"agent"`
	Sessions int    `json:"sessions"`
	LastAt   int64  `json:"last_at"`
}

BrainAgentRead is one agent whose sessions the extraction read: how many distinct sessions, and when the newest of those reads finished (unix ms).

func BrainAgentsSince added in v0.146.0

func BrainAgentsSince(ctx context.Context, q Querier, since int64) ([]BrainAgentRead, error)

BrainAgentsSince lists the agents whose sessions a read went through (status ok) since a moment, most sessions first, then the newest read. A session with no agent recorded counts as claude, the default agent.

type BrainCandidate added in v0.117.2

type BrainCandidate struct {
	SessionID string
	Project   string
	// Cwd and RepoRoot are where the session ran and the repository root
	// found there at ingest ("" outside one), for the extraction to decide
	// which project its memories belong to.
	Cwd, RepoRoot string
	LastEventAt   int64
	// Cursor is the newest event already read; MaxEventID the session's newest.
	Cursor     int64
	MaxEventID int64
	// Ended is set when the session has ended: a short tail can no longer
	// wait for more and is marked read.
	Ended bool
}

BrainCandidate is a session with events the extraction has not read.

func BrainCandidates added in v0.117.2

func BrainCandidates(ctx context.Context, q Querier, since, idleBefore int64, limit int) ([]BrainCandidate, error)

BrainCandidates lists sessions active since `since` and quiet since `idleBefore` (or ended), with events past their cursor, newest first. A session whose short tail was held is left out until it has newer events or ends, and a session marked as automation (MarkBrainAutomation) or as started at the root or home (MarkBrainRootOrHome) always.

func BrainSessionCandidate added in v0.148.0

func BrainSessionCandidate(ctx context.Context, q Querier, sessionID string) (BrainCandidate, bool, error)

BrainSessionCandidate is a session as a read sees it — project, where it ran, whether it ended — for a catch-up read; ok is false when it is gone.

type BrainClaim added in v0.135.0

type BrainClaim struct {
	Src, Dst int64
	Kind     string
}

BrainClaim is an edge a vault's import wants.

type BrainDayProject added in v0.153.0

type BrainDayProject struct {
	Project string `json:"project"`
	Retag   bool   `json:"retag,omitempty"`
	Tokens  int64  `json:"tokens"`
}

BrainDayProject is one project's tokens on one day.

type BrainDaySpend added in v0.148.0

type BrainDaySpend struct {
	// Day is the date, YYYY-MM-DD, in the daemon's time zone; Start is its
	// midnight, unix ms.
	Day     string  `json:"day"`
	Start   int64   `json:"start"`
	Tokens  int64   `json:"tokens"`
	CostUSD float64 `json:"cost_usd"`
	Reads   int     `json:"reads"`
	// Projects is the day's tokens by whose they were, keyed as the
	// window's projects are (project, and retag for the re-tag batches),
	// most tokens first; only those that spent any. They add up to Tokens.
	Projects []BrainDayProject `json:"projects"`
}

BrainDaySpend is one local day of the extraction's reads.

func BucketBrainDays added in v0.148.0

func BucketBrainDays(runs []BrainSpendRow, now time.Time, days int) []BrainDaySpend

BucketBrainDays sums reads into `days` local days ending with now's, oldest first, every day present even when nothing was read. A row outside them is left out. Days follow the calendar, so one with a clock change lasts 23 or 25 hours.

type BrainEdge added in v0.117.1

type BrainEdge struct {
	From   int64   `json:"from"`
	To     int64   `json:"to"`
	Kind   string  `json:"kind"`
	Weight float64 `json:"weight"`
}

BrainEdge is one edge.

type BrainFilter added in v0.117.1

type BrainFilter struct {
	// Agents excludes vault content the user has not allowed agents to read.
	Agents bool
	// Query is words that must each match a memory's title, summary or
	// project, or the name of an entity it is linked to — in any case, with
	// or without accents, and, when few memories match exactly, one or two
	// edits away (brainsearch.go). Matches come best first.
	Query string
	// Project keeps the memories of one project.
	Project string
	// ExcludeProjects are project labels left out of a read that names no
	// Project: the projects of the folders the user excluded from Second
	// Brain (Settings → Second Brain). Opening one of them by Project still
	// shows it; nothing is deleted.
	ExcludeProjects []string
	// Since and Until bound when a memory was made, unix ms; 0 is open.
	Since, Until int64
	// Limit is how many memories at most; their entities come with them.
	Limit int
	// Summaries carries each node's summary. Off, the graph is lighter to
	// read and send, and a node's detail is read on its own.
	Summaries bool
}

BrainFilter narrows the graph read.

type BrainGap added in v0.148.0

type BrainGap struct {
	ID          int64
	RunID       int64
	SessionID   string
	FromEventID int64
	// ToEventID is 0 until the gap is measured.
	ToEventID  int64
	Cursor     int64
	Status     string
	ReadsTotal int
	ReadsDone  int
	Attempts   int
	UpdatedAt  int64
	// RunThrough is the skipping read's through_event_id: what that read
	// had in front of it ended there.
	RunThrough int64
}

BrainGap is one skipped span: the session's events after FromEventID up to and including ToEventID, read up to Cursor so far.

func PendingBrainGaps added in v0.148.0

func PendingBrainGaps(ctx context.Context, q Querier, limit int) ([]BrainGap, error)

PendingBrainGaps lists the measured gaps still to read, oldest read first.

func UnmeasuredBrainGaps added in v0.148.0

func UnmeasuredBrainGaps(ctx context.Context, q Querier) ([]BrainGap, error)

UnmeasuredBrainGaps lists the gaps not measured yet, oldest read first.

type BrainGraph added in v0.117.1

type BrainGraph struct {
	Nodes []BrainNode `json:"nodes"`
	Edges []BrainEdge `json:"edges"`
	Total int         `json:"total"`
	// Terms are a search's words, folded, and the close words that matched
	// them, for the screen to highlight; Close is true when a returned
	// memory is a close match. Both are absent outside a search.
	Terms []string `json:"terms,omitempty"`
	Close bool     `json:"close,omitempty"`
}

BrainGraph is the graph a screen draws: the newest memories that pass the filter (pinned ones first), the entities linked to them, and every edge between what is returned. Total is how many memories pass the filter.

func ReadBrainGraph added in v0.117.1

func ReadBrainGraph(ctx context.Context, q Querier, f BrainFilter) (BrainGraph, error)

ReadBrainGraph reads the graph for a filter.

type BrainHandoffPick added in v0.148.0

type BrainHandoffPick struct {
	Decisions []BrainNode
	Memories  []BrainNode
	Text      string
}

BrainHandoffPick is what a new session in a repository is handed from Second Brain: its current decisions, its other memories, and the text the SessionStart handoff appends ("" when there is neither). GET /v1/brain/handoff shows the same pick, so the screen and the MCP tool name exactly what a session gets.

func BrainHandoff added in v0.125.0

func BrainHandoff(ctx context.Context, q Querier, project string) (BrainHandoffPick, error)

BrainHandoff picks what a new session in a repository is handed.

func (BrainHandoffPick) Count added in v0.148.0

func (p BrainHandoffPick) Count() int

Count is how many memories it hands over, decisions included.

type BrainKeywords added in v0.148.0

type BrainKeywords []string

BrainKeywords is a memory's keywords, stored in brain_nodes.keywords joined with ", " and sent as a JSON array.

func CleanBrainKeywords added in v0.148.0

func CleanBrainKeywords(in []string) BrainKeywords

CleanBrainKeywords trims, de-duplicates (folded) and caps keywords. A comma would split one in two when stored, so it becomes a space.

func ParseBrainKeywords added in v0.148.0

func ParseBrainKeywords(s string) BrainKeywords

ParseBrainKeywords splits the stored form.

func (*BrainKeywords) Scan added in v0.148.0

func (k *BrainKeywords) Scan(v any) error

Scan reads the stored column.

func (BrainKeywords) String added in v0.148.0

func (k BrainKeywords) String() string

String is the stored form.

type BrainLink struct {
	Node BrainNode `json:"node"`
	Kind string    `json:"kind"`
	// Out is true when the edge goes from the node asked about to this one.
	Out    bool    `json:"out"`
	Weight float64 `json:"weight"`
}

BrainLink is a neighbour of a node: the node, and the edge between them.

func BrainNeighbours added in v0.117.1

func BrainNeighbours(ctx context.Context, q Querier, id int64, limit int) ([]BrainLink, error)

BrainNeighbours returns what a node is linked to, strongest first.

type BrainNode added in v0.117.1

type BrainNode struct {
	ID        int64       `json:"id"`
	Kind      string      `json:"kind"`
	Title     string      `json:"title"`
	Summary   string      `json:"summary"`
	Source    BrainSource `json:"source"`
	Manual    bool        `json:"manual"`
	Pinned    bool        `json:"pinned"`
	RunID     int64       `json:"run_id,omitempty"`
	CreatedAt int64       `json:"created_at"`
	UpdatedAt int64       `json:"updated_at"`
	// Vault names the Obsidian vault a node was imported from, or gained a
	// source from (the oldest when several), filled in by the graph read and
	// a node's own read (ADR-079). Absent for a node with no note source.
	Vault string `json:"vault,omitempty"`
	// Degree is how many returned edges touch it, filled in by the graph read.
	Degree int `json:"degree,omitempty"`
	// Rank is how well a memory matched a search, higher first (brainsearch.go);
	// Close is true when some word matched only a word a typo or an ending
	// away. Both are absent outside a search.
	Rank  int  `json:"rank,omitempty"`
	Close bool `json:"close,omitempty"`
	// Keywords are the English keywords the extraction gave a memory
	// (migration 0069); none for one made before them, by hand or imported.
	Keywords BrainKeywords `json:"keywords,omitempty"`
	// SupersededBy is the newest memory with a supersedes edge to this one,
	// filled in by the graph read and a node's own read: the memory is no
	// longer current. Absent while it is.
	SupersededBy int64 `json:"superseded_by,omitempty"`
}

BrainNode is one node of the graph.

func BrainCurrentDecisions added in v0.148.0

func BrainCurrentDecisions(ctx context.Context, q Querier, project string, limit int, agents bool) ([]BrainNode, error)

BrainCurrentDecisions returns a project's decisions that nothing supersedes, newest first, at most limit. agents keeps out what may not reach an MCP client (brainMCPMayRead).

func BrainNodeByEvent added in v0.117.1

func BrainNodeByEvent(ctx context.Context, q Querier, eventID int64) (BrainNode, error)

BrainNodeByEvent returns the memory dropped in by hand from an event, if there is one: dropping the same answer twice keeps one memory.

func BrainProjectMemories added in v0.117.2

func BrainProjectMemories(ctx context.Context, q Querier, project string, limit int) ([]BrainNode, error)

BrainProjectMemories returns a project's pinned memories, then its newest, for a new session's handoff. An imported note is among them only when every vault it came from lets its notes reach agents (ADR-079).

func BrainRecentMemories added in v0.148.0

func BrainRecentMemories(ctx context.Context, q Querier, project string, limit int) ([]BrainNode, error)

BrainRecentMemories returns a project's newest memories of any kind but imported notes, newest first, for a read to be shown what is already kept.

func BrainUntagged added in v0.148.0

func BrainUntagged(ctx context.Context, q Querier, after int64, limit int) ([]BrainNode, error)

BrainUntagged returns the memories without keywords above a memory id, lowest id first, at most limit.

func GetBrainNode added in v0.117.1

func GetBrainNode(ctx context.Context, q Querier, id int64) (BrainNode, error)

GetBrainNode returns one node; ErrBrainNotFound when unknown.

func InsertBrainNode added in v0.117.1

func InsertBrainNode(ctx context.Context, q Querier, v BrainNode, now int64) (BrainNode, bool, error)

InsertBrainNode adds a node and returns it as stored, with created true. Title and summary are clipped to their limits. An entity whose normalized title already exists is not added again: the existing one is returned with created false, so "SQLite" dropped twice is one topic.

func UpdateBrainNode added in v0.117.1

func UpdateBrainNode(ctx context.Context, q Querier, id int64, p BrainPatch, now int64) (BrainNode, error)

UpdateBrainNode applies a patch and returns the node as stored.

type BrainNoteSourceView added in v0.135.0

type BrainNoteSourceView struct {
	VaultID int64    `json:"vault_id"`
	Vault   string   `json:"vault"`
	Path    string   `json:"path"`
	Title   string   `json:"title"`
	Aliases []string `json:"aliases,omitempty"`
	Excerpt string   `json:"excerpt"`
	Mtime   int64    `json:"mtime"`
}

BrainNoteSourceView is one source of a node read on its own: the vault, the file, and that file's own excerpt.

func BrainNodeSources added in v0.135.0

func BrainNodeSources(ctx context.Context, q Querier, nodeID int64) ([]BrainNoteSourceView, error)

BrainNodeSources returns the note files that are sources of a node, oldest first.

type BrainPassage added in v0.117.2

type BrainPassage struct {
	EventID int64
	Ts      int64
	// User is true for the user's prompt, false for the agent's prose.
	User bool
	Text string
}

BrainPassage is one prompt or one answer in a session's main thread.

func BrainOldWindow added in v0.148.0

func BrainOldWindow(ctx context.Context, q Querier, sessionID string, after, through int64, limit int) ([]BrainPassage, error)

BrainOldWindow is what a read before 2026-10-22 had in front of it: the newest `limit` main-thread turns after `after` up to `through`, empty ones counted against the limit and then dropped, ordered by time. The catch-up re-runs that read's cut on it to find what it skipped.

func BrainPassages added in v0.117.2

func BrainPassages(ctx context.Context, q Querier, sessionID string, after int64, limit int) ([]BrainPassage, error)

BrainPassages returns a session's main-thread prompts and prose after an event id, oldest first by event id, at most limit of them (the oldest kept when there are more). Empty passages are left out before the limit, so a full page means more may follow: a read that sends only part of them moves its cursor to the last one it sent, and the next read goes on from there.

func BrainPassagesBetween added in v0.148.0

func BrainPassagesBetween(ctx context.Context, q Querier, sessionID string, after, through int64, limit int) ([]BrainPassage, error)

BrainPassagesBetween is BrainPassages for the events after `after` up to and including `through`: a read never goes past the event it was told to stop at, and a catch-up read stays inside its gap.

type BrainPatch added in v0.117.1

type BrainPatch struct {
	Kind    *string `json:"kind"`
	Title   *string `json:"title"`
	Summary *string `json:"summary"`
	Pinned  *bool   `json:"pinned"`
}

BrainPatch is a change to a node; nil fields stay.

type BrainProjectCount added in v0.117.1

type BrainProjectCount struct {
	Project string `json:"project"`
	Count   int    `json:"count"`
}

BrainProjectCount is one project with how many memories it has.

func BrainProjects added in v0.117.1

func BrainProjects(ctx context.Context, q Querier, agents ...bool) ([]BrainProjectCount, error)

BrainProjects lists the projects memories belong to, most memories first, for the screen's filter.

type BrainProjectSpend added in v0.148.0

type BrainProjectSpend struct {
	Project  string  `json:"project"`
	Retag    bool    `json:"retag,omitempty"`
	Reads    int     `json:"reads"`
	Tokens   int64   `json:"tokens"`
	CostUSD  float64 `json:"cost_usd"`
	Memories int     `json:"memories"`
}

BrainProjectSpend is one project's share of the reads since a moment: how many asked claude, their tokens and cost, and the memories the reads with status ok kept. Retag marks the one row that is not a project: the re-tag batches (BrainRetagSession), with Project "", Reads the batches and Memories the memories they gave keywords.

func BrainSpendByProject added in v0.148.0

func BrainSpendByProject(ctx context.Context, q Querier, since int64) ([]BrainProjectSpend, error)

BrainSpendByProject groups the reads since a moment by their session's project ("" when the session has none or is gone), most tokens first, the re-tag batches in a row of their own. A project whose reads were all skipped is left out.

type BrainReadSession added in v0.120.0

type BrainReadSession struct {
	SessionID string
	Project   string
	Memories  int
	// LastEventAt is when the session last did something, unix ms: a
	// catch-up tells the sessions from before the yes by it.
	LastEventAt int64
}

BrainReadSession is a session active since a moment that the extraction has read at least once without failing, with the memories its reads kept.

func BrainReadSessions added in v0.120.0

func BrainReadSessions(ctx context.Context, q Querier, since int64) ([]BrainReadSession, error)

BrainReadSessions lists the sessions active since `since` with a read that did not fail: the "read" side of a build's progress. A session marked as started at the root or home was never read and is not listed.

type BrainRun added in v0.117.2

type BrainRun struct {
	ID             int64   `json:"id"`
	SessionID      string  `json:"session_id"`
	FromEventID    int64   `json:"from_event_id"`
	ThroughEventID int64   `json:"through_event_id"`
	Status         string  `json:"status"`
	Model          string  `json:"model,omitempty"`
	TokensIn       int64   `json:"tokens_in"`
	TokensOut      int64   `json:"tokens_out"`
	CostUSD        float64 `json:"cost_usd"`
	Nodes          int     `json:"nodes"`
	Error          string  `json:"error,omitempty"`
	StartedAt      int64   `json:"started_at"`
	FinishedAt     int64   `json:"finished_at"`
	// GapID is the catch-up gap a read went through (brain_gaps), 0 for a
	// regular read. Held marks a read that left a short, still-open tail
	// unread so it is read with what comes next (migration 0068).
	GapID int64 `json:"gap_id,omitempty"`
	Held  bool  `json:"-"`
	// Project, Title and Agent are the session's, joined in when listed;
	// Title is its own name or, without one, its first stored prompt.
	Project string `json:"project,omitempty"`
	Title   string `json:"title,omitempty"`
	Agent   string `json:"agent,omitempty"`
}

BrainRun is one read of one session by the automatic extraction.

func BrainRunsOf added in v0.157.0

func BrainRunsOf(ctx context.Context, q Querier, sessionID string) ([]BrainRun, error)

BrainRunsOf lists one session's reads and marks, oldest first.

func LastBrainRuns added in v0.117.2

func LastBrainRuns(ctx context.Context, q Querier, limit int) ([]BrainRun, error)

LastBrainRuns returns the newest reads of sessions that did something (not skipped, not a re-tag batch), newest first.

type BrainSource added in v0.117.1

type BrainSource struct {
	SessionID string `json:"session_id,omitempty"`
	EventID   int64  `json:"event_id,omitempty"`
	Ts        int64  `json:"ts,omitempty"`
	Project   string `json:"project,omitempty"`
}

BrainSource is where a memory was taken from: a session, the moment in it, and its project. Empty for a line typed into the quick capture.

func BrainNoteSource added in v0.117.1

func BrainNoteSource(ctx context.Context, q Querier, eventID int64) (BrainSource, string, error)

BrainNoteSource returns where an assistant note came from — its session, time and project — and its text, for a memory dropped from it. An event that is not main-thread prose is ErrBrainNotFound.

func (BrainSource) AddToFrame added in v0.130.0

func (s BrainSource) AddToFrame(data map[string]any)

AddToFrame puts the session and the project, each only when known, on an added memory's `brain` frame, so a screen can show it arriving from that session's tab (03-contracts.md § Second Brain, Live).

type BrainSpendRow added in v0.148.0

type BrainSpendRow struct {
	FinishedAt int64
	Tokens     int64
	CostUSD    float64
	Read       bool
	Project    string
	Retag      bool
}

BrainSpendRow is one read's spend: when it finished, its tokens (input and output together, as brain_runs keeps them) and cost, and whether claude was asked at all — a skipped session costs nothing and is no read — and whose it was: the read session's project ("" when it has none or is gone), or Retag for a re-tag batch, as BrainSpendByProject groups them.

func BrainSpendRows added in v0.148.0

func BrainSpendRows(ctx context.Context, q Querier, since int64) ([]BrainSpendRow, error)

BrainSpendRows lists every read that finished since a moment, oldest first.

type BrainVault added in v0.135.0

type BrainVault struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
	Path string `json:"path"`
	// Agents is whether its notes may reach an agent: a new session's
	// handoff, the extraction's list of topics. Off unless the user turns
	// it on (ADR-079).
	Agents    bool   `json:"agents"`
	Notes     int    `json:"notes"`
	ScannedAt int64  `json:"scanned_at,omitempty"`
	ScanMs    int64  `json:"scan_ms"`
	Error     string `json:"error,omitempty"`
	CreatedAt int64  `json:"created_at"`
}

BrainVault is one imported vault.

func GetBrainVault added in v0.135.0

func GetBrainVault(ctx context.Context, q Querier, id int64) (BrainVault, error)

GetBrainVault returns one vault; ErrVaultNotFound when unknown.

func InsertBrainVault added in v0.135.0

func InsertBrainVault(ctx context.Context, q Querier, name, path string, agents bool, now int64) (BrainVault, error)

InsertBrainVault adds a vault; ErrVaultExists when its path is taken.

func ListBrainVaults added in v0.135.0

func ListBrainVaults(ctx context.Context, q Querier) ([]BrainVault, error)

ListBrainVaults returns the vaults, oldest first.

type BrainVaultNote added in v0.135.0

type BrainVaultNote struct {
	ID      int64
	VaultID int64
	Path    string
	NodeID  int64
	Title   string
	Aliases []string
	// Keys are the title and aliases normalised (NormTitle): what makes two
	// notes, or a note and a memory, one node.
	Keys    []string
	Links   []string
	Tags    []string
	Project string
	Excerpt string
	Mtime   int64
	Size    int64
}

BrainVaultNote is one note file of a vault: the source mark on its node.

func BrainVaultNotes added in v0.135.0

func BrainVaultNotes(ctx context.Context, q Querier, vaultID int64) ([]BrainVaultNote, error)

BrainVaultNotes returns a vault's note rows.

type BranchSpend added in v0.111.0

type BranchSpend struct {
	Branch   string   `json:"branch"`
	Sessions int      `json:"sessions"`
	Agents   []string `json:"agents"`
	CostUSD  float64  `json:"cost_usd"`
	LastAt   int64    `json:"last_at"`
}

BranchSpend is what Caprock's sessions on one branch of a repository cost: the sessions recorded on it (sessions.git_branch, the branch the session was on when Caprock saw it), the agents among them, the sum of their session_stats.cost_usd and the newest event of any of them.

type CallTool added in v0.95.0

type CallTool struct {
	Tool  string
	Input json.RawMessage
}

CallTool is one tool request of a model call, with its raw input.

type ChatCounts added in v0.126.0

type ChatCounts struct {
	Chats    int `json:"chats"`
	Archived int `json:"archived"`
}

ChatCounts is how many chats there are: those the list shows, and those archived out of it.

func CountChats added in v0.126.0

func CountChats(ctx context.Context, q Querier) (ChatCounts, error)

CountChats counts the chats, archived and not, off idx_sessions_chat.

type ChatScope added in v0.126.0

type ChatScope int

ChatScope says which sessions a list holds with respect to chats.

const (
	// ChatsIncluded lists every session, chats among them (the default).
	ChatsIncluded ChatScope = iota
	// ChatsExcluded lists no chat: the work sessions only.
	ChatsExcluded
	// ChatsOnly lists the chats only, archived or not by Archived.
	ChatsOnly
)

type CompactStep added in v0.114.0

type CompactStep struct {
	// Rewritten is how many rows lost base64; Freed is how many payload bytes
	// that took out of them.
	Rewritten int
	Freed     int64
	// Done is true once the last window has been examined.
	Done bool
}

CompactStep is what one step of the payload compaction did.

type DailyStat

type DailyStat struct {
	Day         string  `json:"day"`
	Project     string  `json:"project"`
	Model       string  `json:"model"`
	TokensTotal int64   `json:"tokens_total"`
	CostUSD     float64 `json:"cost_usd"`
	Sessions    int64   `json:"sessions"`
}

DailyStat mirrors daily_stats.

func Daily

func Daily(ctx context.Context, q Querier, from string) ([]DailyStat, error)

Daily returns daily_stats for the last `days` days (day >= from), oldest first.

type Deciles added in v0.114.0

type Deciles struct {
	N    int       `json:"n"`
	Q    []float64 `json:"q"`
	Mean float64   `json:"mean"`
}

Deciles is a distribution as its sample count and eleven values: the minimum, every tenth percentile, and the maximum, ascending; and its mean. The cockpit's chart needs the mean: a bar's burn rate is its active hours' cost over those hours, a mean, and a mean set against a median of a skewed distribution reads high every time (the owner's 30 days on 2026-10-13: median $3.82/h, mean $8.25/h).

type DrillHint added in v0.70.0

type DrillHint struct {
	Kind   string  `json:"kind"` // failures, output, repeats
	Key    string  `json:"key"`
	Text   string  `json:"text"`
	Weight float64 `json:"-"`
}

DrillHint is one fact and the row it is about. Weight orders hints: the share of the tool's calls, output or failures the fact accounts for.

type DrillOptions added in v0.70.0

type DrillOptions struct {
	Tool   string
	FromMs int64
	ToMs   int64 // the trend's end; 0 means now as the caller sees it
	Agent  AgentFilter
	Home   string
	Rows   int
	Trend  int
}

DrillOptions bounds a drill.

type DrillRow added in v0.70.0

type DrillRow struct {
	Key      string  `json:"key"`
	Calls    int64   `json:"calls"`
	Results  int64   `json:"results,omitempty"`
	Failures int64   `json:"failures,omitempty"`
	Bytes    int64   `json:"bytes,omitempty"`
	Trend    []int64 `json:"trend,omitempty"`
}

DrillRow is one group of calls.

type EndedPID added in v0.116.0

type EndedPID struct {
	SessionID   string
	PID         int
	StartedAt   int64
	LastEventAt int64
}

EndedPID is an ended session that ran in a process: when it started and when it was last heard from, unix ms.

type EventFilter added in v0.92.0

type EventFilter struct {
	// MainOnly keeps the main thread's events: no subagent's (agent_id set)
	// and no transcript sidechain line. A parent running subagents in parallel
	// logs hundreds of their events an hour, and a window of its newest few
	// hundred events held none of the parent's own calls.
	MainOnly bool
	// Kinds keeps only these kinds; empty keeps every kind.
	Kinds []string
}

EventFilter narrows a page of a session's events.

type EventTLDR added in v0.128.0

type EventTLDR struct {
	EventID   int64
	Text      string
	Model     string
	CostUSD   float64
	CreatedAt int64
}

EventTLDR is one kept squeeze.

func GetEventTLDR added in v0.128.0

func GetEventTLDR(ctx context.Context, q Querier, eventID int64) (EventTLDR, bool, error)

GetEventTLDR returns the squeeze kept for an event; ok is false when there is none.

type EventsGen added in v0.135.0

type EventsGen struct {
	Gen   int64
	MaxID int64
}

EventsGen identifies the state of a session's events: equal values mean its events are as they were. Gen is its rewrite generation (migration 0063), which triggers move in the same transaction as every update or delete of its events, whichever code writes them; MaxID is its newest row id, which every insert moves, because a new row takes a rowid above every existing one. Within one Gen only inserts happen and each raises MaxID, so the pair never repeats. Both come from one statement, one snapshot, and one index lookup each (idx_events_session_id is (session_id, id)). Read it before the events it guards, so what is read is never older than it.

func ReadEventsGen added in v0.135.0

func ReadEventsGen(ctx context.Context, q Querier, sessionID string) (EventsGen, error)

ReadEventsGen reads a session's EventsGen; zero for a session with no events ever written.

func (EventsGen) Older added in v0.135.0

func (g EventsGen) Older(o EventsGen) bool

Older reports whether g was read before o: Gen only grows, and within one Gen only inserts happen, which only raise MaxID.

type GitHubPR added in v0.153.0

type GitHubPR struct {
	Number    int
	URL       string
	Title     string
	Head      string
	State     string // open | closed | merged
	CreatedAt int64
	MergedAt  int64
	ClosedAt  int64
	UpdatedAt int64
}

GitHubPR is one pull request header from a GitHub list (github_prs).

type GitHubWindow added in v0.159.0

type GitHubWindow struct {
	// Known says github_prs holds any row of the repository at all: a
	// repository the Pipeline never read has no record, which is not "none".
	Known bool
	// Merged are the numbers of the pull requests merged in the window;
	// OpenedAt the creation times (unix ms) of those opened in it.
	Merged   []int
	OpenedAt []int64
}

GitHubWindow is what github_prs holds for one repository in a window.

func GitHubPRsIn added in v0.159.0

func GitHubPRsIn(ctx context.Context, q Querier, repo string, from, to int64) (GitHubWindow, error)

GitHubPRsIn reads repo's ("owner/name") pull requests merged and opened in [from, to) from github_prs.

type HandoffGroup added in v0.61.0

type HandoffGroup struct {
	Sessions   int     `json:"sessions"`
	Reached    int     `json:"reached"`
	MedianMin  float64 `json:"median_min"`
	MedianCall float64 `json:"median_calls"`
}

HandoffGroup is how one arm of the handoff comparison got on: of the sessions in it, how many reached a first edit, and how long and how many tool calls that took.

func HandoffEffect added in v0.61.0

func HandoffEffect(ctx context.Context, q Querier) (served, withheld HandoffGroup, err error)

HandoffEffect compares sessions that were handed the last session's note with sessions that could have been and were not. The measure is the first edit: how long, and how many tool calls, a session spends finding its footing before it changes anything. A handoff that works should shorten it.

type HermesCost added in v0.122.0

type HermesCost struct {
	TotalUSD float64 `json:"total_usd"`
	// ActualUSD is what the provider reported billing; EstimatedUSD is
	// Hermes's estimate from its own price list. Subscription calls are
	// priced at zero and counted in IncludedTurns.
	ActualUSD     float64 `json:"actual_usd"`
	EstimatedUSD  float64 `json:"estimated_usd"`
	IncludedTurns int64   `json:"included_turns,omitempty"`
	// UnpricedTurns carry tokens and no cost: Hermes had no price for them.
	UnpricedTurns int64 `json:"unpriced_turns,omitempty"`
	// BackgroundUSD is the part nobody was watching as it ran — cron jobs,
	// a chat through Hermes's gateway, one-shot runs — and Sources splits it.
	BackgroundUSD float64        `json:"background_usd"`
	Sources       []HermesSource `json:"sources,omitempty"`
}

HermesCost is what Hermes Agent's sessions cost in a range, split the two ways the Cost screen shows it (ADR-069): by what kind of figure it is, and by whether a person was there.

Hermes prices its own calls and records whether a figure is the provider's invoice or its own estimate; the importer copies that onto each event's payload as `cost_basis`, and Hermes's session source as `hermes_source` and `background`. Nothing here is priced by Caprock's table.

func HermesSpend added in v0.122.0

func HermesSpend(ctx context.Context, q Querier, fromMs int64) (*HermesCost, error)

HermesSpend sums Hermes's turns since fromMs; nil when there are none, so a machine without Hermes carries no empty panel.

Scoped through the Hermes sessions first, so the events walked are theirs (idx_events_session_ts): on a machine without Hermes it reads nothing.

type HermesSource added in v0.122.0

type HermesSource struct {
	Source  string  `json:"source"`
	CostUSD float64 `json:"cost_usd"`
}

HermesSource is the background spend of one Hermes session source.

type HistoryTotals

type HistoryTotals struct {
	Sessions      int64   `json:"sessions"`
	OwnedSessions int64   `json:"owned_sessions"`
	Turns         int64   `json:"turns"`
	ToolCalls     int64   `json:"tool_calls"`
	FilesTouched  int64   `json:"files_touched"`
	CostUSD       float64 `json:"cost_usd"`
	AvgSessionSec float64 `json:"avg_session_sec"`
	Days          int64   `json:"days"`
	// Unpriced is the volume in range with no pricing row, so CostUSD excludes
	// it. Omitted when everything was priced. History's headline claims the
	// numbers are "measured, not estimated", which a silently incomplete total
	// would make false.
	Unpriced *Unpriced `json:"unpriced,omitempty"`
	// Background is known internal model usage, reported separately rather than
	// counted as sessions or turns the user started.
	Background *BackgroundUsage `json:"background,omitempty"`
}

HistoryTotals is the all-time (or ranged) cross-session summary for the History screen.

func History

func History(ctx context.Context, q Querier, fromMs int64) (HistoryTotals, error)

History computes cross-session totals since fromMs. A caller that also needs Summarize for the same fromMs passes its answer to HistoryFrom instead: the per-kind totals, the unpriced and the background volume are the same scans in both, and on an all-time range they are most of the cost.

func HistoryFrom added in v0.135.0

func HistoryFrom(ctx context.Context, q Querier, fromMs int64, sum Summary) (HistoryTotals, error)

HistoryFrom is History given Summarize's answer for the same fromMs (no agent filter): turns, tool calls, cost, unpriced and background volume are taken from it rather than scanned a second time. The per-kind scan is the one sumKinds makes, with the same filter and the same index, so the figures are identical, not merely close (TestHistoryFromMatchesHistory).

It was a second pass over every event in the range: dropping it, with the unpriced and background queries it repeated, took one all-time history from a best of 0.66-1.33s to 0.49-0.92s on a 181k-event database (2026-10-18, loaded machine; resource-usage audit F13).

type InboxItem added in v0.115.0

type InboxItem struct {
	ID   int64  `json:"id"`
	Text string `json:"text"`
	// Files are paths under <data_dir>/inbox, written by the daemon.
	Files []string `json:"files"`
	// ProjectID is the project it was saved to; 0 means the Inbox itself.
	ProjectID int64 `json:"project_id,omitempty"`
	// ProjectRoot and ProjectName are the project's, joined in when listed.
	ProjectRoot string `json:"project_root,omitempty"`
	ProjectName string `json:"project_name,omitempty"`
	// FromDevice is the paired device's name; empty when saved on the machine.
	FromDevice string `json:"from_device,omitempty"`
	CreatedAt  int64  `json:"created_at"`
}

InboxItem is one thing saved for later (migration 0053): a note, a link or a photo, from the phone or the machine, to start a chat from.

func GetInboxItem added in v0.115.0

func GetInboxItem(ctx context.Context, q Querier, id int64) (InboxItem, error)

GetInboxItem returns one item; ErrInboxNotFound when unknown.

func InsertInboxItem added in v0.115.0

func InsertInboxItem(ctx context.Context, q Querier, v InboxItem, now int64) (InboxItem, error)

InsertInboxItem adds an item and returns it as listed.

func ListInbox added in v0.115.0

func ListInbox(ctx context.Context, q Querier) ([]InboxItem, error)

ListInbox returns the saved items, newest first.

type KnownPR added in v0.153.0

type KnownPR struct {
	Number int    `json:"number"`
	URL    string `json:"url"`
	Title  string `json:"title,omitempty"`
	// State is open, closed or merged as GitHub last listed it; without a
	// listed header, merged or closed when a session recorded that, else
	// empty (not known: an ended session is not a merged pull request).
	State string `json:"state,omitempty"`
	// At is when it last moved (unix ms): merged, else closed, else its
	// newest activity — GitHub's updated_at or a session's last command on
	// it. A period keeps the pull requests whose At falls in it.
	At    int64   `json:"at"`
	Spend PRSpend `json:"spend"`
	// contains filtered or unexported fields
}

KnownPR is a pull request of a repository Caprock knows of locally, and the agent work recorded for it.

func KnownPRs added in v0.153.0

func KnownPRs(ctx context.Context, q Querier, repoRoot, repo string) ([]KnownPR, error)

KnownPRs is every pull request of repo ("owner/name") in github_prs or session_prs, each charged by SpendByPR over the sessions of repoRoot, the same way the board charges its cards. For a head branch two share, the open one owns it, else the most recently moved (SpendByPR's order). The order is by number, newest first.

type LivePID added in v0.101.0

type LivePID struct {
	SessionID string
	PID       int
}

LivePID is a session that has not ended and the process it runs in.

func LivePIDs added in v0.101.0

func LivePIDs(ctx context.Context, q Querier) ([]LivePID, error)

LivePIDs lists the sessions not ended that have a process id: the ones the resource meter can measure. Sessions without one (an older shim's rows, a transcript with no process behind it) are left out.

type ModelShare

type ModelShare struct {
	Model   string  `json:"model"`
	Tokens  int64   `json:"tokens"`
	CostUSD float64 `json:"cost_usd"`
	Turns   int64   `json:"turns"`
	// Output is what the model generated, which is the part of a token total
	// that is entirely this model's work and entirely at the top rate. The
	// combined figure is ~99% cache read on this workload — a number that is
	// real, is nearly free, and swamps everything it is added to.
	Output int64 `json:"output"`
	// CacheRead is the context this model re-read: the conversation being
	// re-sent on every turn. It is the base of the context tax, kept per model
	// because cache-read rates differ by more than the table's usual 0.1x --
	// Fable 5.1 and Mythos 5.1 read at 0.025x, so one blended rate would be
	// wrong for any mixed workload.
	CacheRead int64 `json:"cache_read"`
}

ModelShare is tokens/cost per model.

type ModelTokens added in v0.70.0

type ModelTokens struct {
	Model        string
	In, Out      int64
	CacheRead    int64
	CacheWrite   int64
	CacheWrite1h int64
}

ModelTokens is one model's tokens by type, which the pricing table turns into what each type of token cost.

func SubagentTokensByModel added in v0.138.0

func SubagentTokensByModel(ctx context.Context, q Querier, from, to int64) ([]ModelTokens, error)

SubagentTokensByModel sums, per model, the tokens of Claude Code's subagent turns in [from, to) that were priced: the volume "what if they ran on Haiku" is computed from. Turns with no stored cost are left out (an unpriced model, or a fork's copy of a turn paid elsewhere).

func SubagentTokensByModelSkip added in v0.159.0

func SubagentTokensByModelSkip(ctx context.Context, q Querier, from, to int64, skip string) ([]ModelTokens, error)

SubagentTokensByModelSkip is SubagentTokensByModel with a clause on session_id appended: the Week passes its hand-run filter (Week.SkipSQL).

func TokensByModel added in v0.70.0

func TokensByModel(ctx context.Context, q Querier, from int64) ([]ModelTokens, error)

TokensByModel sums each model's tokens by type since from.

type ModuleDoc added in v0.131.0

type ModuleDoc struct {
	ID        string          `json:"id"`
	Data      json.RawMessage `json:"data"`
	CreatedAt int64           `json:"created_at"`
	UpdatedAt int64           `json:"updated_at"`
}

ModuleDoc is one document a private module keeps (migration 0061, ADR-076). Data is a JSON object; the store never reads inside it.

func GetModuleDoc added in v0.131.0

func GetModuleDoc(ctx context.Context, q Querier, module, collection, id string) (ModuleDoc, error)

GetModuleDoc returns one document; ErrModuleDocNotFound when absent.

func ListModuleDocs added in v0.131.0

func ListModuleDocs(ctx context.Context, q Querier, module, collection, after string, limit int) ([]ModuleDoc, error)

ListModuleDocs returns a collection's documents by id, those after `after` (exclusive), at most limit.

func SetModuleDoc added in v0.131.0

func SetModuleDoc(ctx context.Context, q Querier, module, collection, id string, data []byte, now int64) (ModuleDoc, error)

SetModuleDoc writes a document whole, keeping when it was first made.

func UpdateModuleDoc added in v0.131.0

func UpdateModuleDoc(ctx context.Context, q Querier, module, collection, id string, patch map[string]json.RawMessage, now int64) (ModuleDoc, error)

UpdateModuleDoc merges fields into an existing document's top level; a field set to null is removed. ErrModuleDocNotFound when there is none. Run it in a transaction so a concurrent update is not lost.

type OverlapPeer added in v0.116.0

type OverlapPeer struct {
	SessionID string   `json:"session_id"`
	StartedAt int64    `json:"started_at"`
	Files     []string `json:"files"`
}

OverlapPeer is another live session in the same checkout, and the files both have edited in the window (empty when they share only the folder).

type PRAction added in v0.70.0

type PRAction struct {
	SessionID string
	URL       string // empty for an action recorded without one ("closed")
	Number    int
	Title     string
	Action    string // created | merged | closed | edited | commented
	Ts        int64
}

PRAction is one recorded `gh pr` command: what it did to which PR, and when.

type PRRef added in v0.116.0

type PRRef struct {
	URL    string
	Branch string
}

PRRef names a pull request for SpendByPR: its link and head branch.

type PRSpend added in v0.116.0

type PRSpend struct {
	CostUSD float64 `json:"cost_usd"`
	// Sessions counts the sessions charged to it; Live those of them not
	// ended — for a session cut between several, only the newest one's.
	Sessions int      `json:"sessions"`
	Live     int      `json:"live"`
	Agents   []string `json:"agents"`
	// ByBranch and BySlice say through which way the cost came: the
	// sessions on the head branch, and those cut at their pull requests.
	ByBranch float64 `json:"by_branch"`
	BySlice  float64 `json:"by_slice"`
	// Shared counts the sessions charged to it only in part: each worked on
	// other pull requests too and was cut between them.
	Shared int `json:"shared,omitempty"`
	// The tokens of the same work: input, output, cache reads and writes.
	TokensIn   int64 `json:"tokens_in"`
	TokensOut  int64 `json:"tokens_out"`
	CacheRead  int64 `json:"cache_read"`
	CacheWrite int64 `json:"cache_write"`
	// Parts splits CostUSD by the sign-in each session ran on, for the plan
	// figures (internal/planshare); they sum to CostUSD.
	Parts SpendParts `json:"parts,omitempty"`
}

PRSpend is the agent work Caprock recorded for one pull request.

type PageCounts added in v0.114.0

type PageCounts struct {
	PageSize int64
	Pages    int64
	Free     int64
}

PageCounts is the database file in pages.

func (PageCounts) Bytes added in v0.114.0

func (p PageCounts) Bytes() int64

Bytes is the file's size; FreeBytes the freelist's.

func (PageCounts) FreeBytes added in v0.114.0

func (p PageCounts) FreeBytes() int64

type PathShare added in v0.12.2

type PathShare struct {
	Path    string  `json:"path"`
	Tokens  int64   `json:"tokens"`
	CostUSD float64 `json:"cost_usd"`
	Turns   int64   `json:"turns"`
	// Unattributed and Outside mark the two rows that are buckets rather than
	// directories, so the UI does not have to know the sentinels' spelling.
	// Unattributed is the turns that ran before their session touched any file;
	// Outside is the turns whose most recent touch was not in this repository.
	// Both are rendered as their own thing and never as a path.
	Unattributed bool `json:"unattributed,omitempty"`
	Outside      bool `json:"outside,omitempty"`
	// TokensPct and CostPct are this row's share of the REPOSITORY's total,
	// including the unattributed bucket — so each column sums to 100% and the
	// unattributed share is visible as its own number instead of being hidden
	// in a denominator.
	//
	// Both are sent because they genuinely differ: cost per token varies by
	// model, so a directory worked on by a cheap model is a larger share of the
	// tokens than of the money. Sending one would leave the reader to assume it
	// described both.
	//
	// They are computed here rather than in the panel because the denominator
	// is the repository total, which the panel only has after summing rows it
	// may be truncating. Values are floored to one decimal on the client
	// (fmtPct), never rounded up.
	TokensPct float64 `json:"tokens_pct"`
	CostPct   float64 `json:"cost_pct"`
}

PathShare is tokens/cost for one directory inside a repository, charged by what the repository's TURNS touched rather than by where a session was launched (see touch.go).

Path is the directory relative to the repository root, written from it so it reads as a path — "/", "/services/api". Two values are NOT paths: UnattributedPath (turns that ran before their session touched any file) and OutsidePath (turns whose most recent touch was outside the repository). Callers must render both as their own thing and never as a directory — see Unattributed and Outside.

Turns replaces the old Sessions count. A session touches many directories, so it cannot be counted once per directory row without the column summing to more than the repository's own session count; a TURN is charged to exactly one row by construction, so turns partition and add up.

type PendingPermission added in v0.73.0

type PendingPermission struct {
	SessionID string
	PromptID  string
	Tool      string
	Detail    string
	Always    string
	SinceMs   int64
	Input     string
	ToolUseID string
	AgentID   string
	AgentType string
}

PendingPermission is the stored half of one permission prompt an owned session is waiting on (migrations 0039, 0042, 0043). The agents package owns its meaning; the store only keeps it across a daemon restart.

func ListPendingPermissions added in v0.78.2

func ListPendingPermissions(ctx context.Context, q Querier, sessionID string) ([]PendingPermission, error)

ListPendingPermissions returns the prompts a session waits on, oldest first.

type Project added in v0.75.0

type Project struct {
	ID            int64  `json:"id"`
	Root          string `json:"root"`
	Name          string `json:"name"`
	Kind          string `json:"kind"`   // repo | folder
	Source        string `json:"source"` // seed | session | folder | new | clone
	RemoteURL     string `json:"remote_url,omitempty"`
	DefaultBranch string `json:"default_branch,omitempty"`
	AddedAt       int64  `json:"added_at"`
	Pinned        bool   `json:"pinned"`
	Sort          int64  `json:"sort"`
	Defaults      string `json:"-"` // raw JSON; the API decodes it
	ArchivedAt    int64  `json:"archived_at,omitempty"`
}

Project is one row of the projects list (migration 0041).

func GetProject added in v0.75.0

func GetProject(ctx context.Context, q Querier, id int64) (Project, error)

GetProject returns one project by id, archived or not.

func GetProjectByRoot added in v0.75.0

func GetProjectByRoot(ctx context.Context, q Querier, root string) (Project, error)

GetProjectByRoot returns the project whose root is root, archived or not.

func InsertProject added in v0.75.0

func InsertProject(ctx context.Context, q Querier, p Project) (Project, bool, error)

InsertProject adds p, or — when its root is already a row — lists that row again (an add of an unlisted project brings it back) and returns it. The existing row's name and settings are kept.

func ListProjects added in v0.75.0

func ListProjects(ctx context.Context, q Querier, withArchived bool) ([]Project, error)

ListProjects returns the listed projects (archived ones too when withArchived), pinned first, then by sort, then by name.

type ProjectActivity added in v0.75.0

type ProjectActivity struct {
	Dir          string
	Total        int64
	Live         int64
	Waiting      int64
	LastActivity int64
	CostToday    float64
}

ProjectActivity is what sessions say about one directory key — a repository root, or the cwd of a session outside any repository.

type ProjectPatch added in v0.75.0

type ProjectPatch struct {
	Name     *string
	Pinned   *bool
	Sort     *int64
	Defaults *string
}

ProjectPatch is what PATCH /v1/projects/{id} may change; nil leaves a field.

type ProjectShare

type ProjectShare struct {
	Project string `json:"project"`
	// Agent is set when every session in this row came from one agent, so the
	// dashboard can say which. Empty when a repository was worked on with
	// both — labelling it either way would be wrong, and the per-session
	// labels below still answer it.
	Agent    string  `json:"agent,omitempty"`
	Tokens   int64   `json:"tokens"`
	CostUSD  float64 `json:"cost_usd"`
	Sessions int64   `json:"sessions"`
	// Dir is the directory the row is keyed on — the repository root, or the
	// session's own directory when it is outside any repository. It is what
	// GET /v1/sessions?dir= takes to list this row's sessions, so the
	// dashboard can open a terminal in the project. Empty for the row of
	// spend whose session was deleted, which has no directory to open.
	Dir   string      `json:"dir,omitempty"`
	Paths []PathShare `json:"paths,omitempty"`
	Spark *Spark      `json:"spark,omitempty"`
	// RepoURL is the repository's web address, from its git remote; set by
	// the API, empty when there is no remote it can link to.
	RepoURL string `json:"repo_url,omitempty"`
	// LastPR is the latest pull request a session in this row opened or
	// merged; set by the API.
	LastPR *SessionPR `json:"last_pr,omitempty"`
}

ProjectShare is tokens/cost per REPOSITORY. Sessions is how many distinct sessions touched it in the range — the "who is working in this repo" half of the question; cost alone does not answer it.

Paths is the breakdown one level down: what each top-level directory inside the repository cost. On a monorepo that is the difference between "caprock cost $1,662" and "ui was $400 of it", which is the question a budget actually asks. It is present only when the repository has more than one such directory — a single-directory repo would just repeat its own total. Spark is the per-bucket series behind the row's sparkline, present only when the caller asked for one. It is deliberately NOT repeated on PathShare: a sparkline per directory would multiply the payload of a polled endpoint for a picture nobody sees until they expand the row.

type Querier

type Querier interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Querier is satisfied by *sql.DB and *sql.Tx.

func Prepared added in v0.135.0

func Prepared(q Querier) (Querier, func())

Prepared wraps q so each distinct statement is prepared once and reused, and returns the function that closes them. A q that cannot prepare is returned as it is.

type QueryStat added in v0.113.0

type QueryStat struct {
	Query   string `json:"query"`
	Caller  string `json:"caller"`
	Times   int64  `json:"times"`
	TotalMs int64  `json:"total_ms"`
	MaxMs   int64  `json:"max_ms"`
	Rows    int64  `json:"rows"`
}

QueryStat is the running tally of one statement that has been slow at least once since the daemon started.

type QueuedMessage added in v0.104.0

type QueuedMessage struct {
	ID        int64  `json:"id"`
	SessionID string `json:"session_id"`
	Text      string `json:"text"`
	CreatedAt int64  `json:"created_at"`
	UpdatedAt int64  `json:"updated_at"`
	// Via is where the message came from: "telegram" for a forward to the
	// paired bot (migration 0064, ADR-081), "" for Caprock's own field.
	Via string `json:"via,omitempty"`
}

QueuedMessage is one message waiting for a session's turn to end (migration 0047, ADR-053).

func AddQueued added in v0.104.0

func AddQueued(ctx context.Context, q Querier, sessionID, text string, now time.Time) (QueuedMessage, error)

AddQueued puts text at the end of a session's queue.

func AddQueuedVia added in v0.137.0

func AddQueuedVia(ctx context.Context, q Querier, sessionID, text, via string, now time.Time) (QueuedMessage, error)

AddQueuedVia is AddQueued for a message that came from elsewhere ("telegram").

func GetQueued added in v0.104.0

func GetQueued(ctx context.Context, q Querier, sessionID string, id int64) (QueuedMessage, error)

GetQueued returns one message of a session's queue; ErrQueuedNotFound when the session holds no such id.

func ListQueued added in v0.104.0

func ListQueued(ctx context.Context, q Querier, sessionID string) ([]QueuedMessage, error)

ListQueued returns a session's queue, oldest first: the order it is sent in.

type RateDay added in v0.122.0

type RateDay struct {
	Day string `json:"day"`
	RateSpan
}

RateDay is one local day's span.

type RateLimitSnapshot added in v0.4.0

type RateLimitSnapshot struct {
	Window         string  `json:"window"`
	Ts             int64   `json:"ts"` // unix ms received
	UsedPercentage float64 `json:"used_percentage"`
	ResetsAt       int64   `json:"resets_at"` // unix seconds
}

RateLimitSnapshot is one window's rate-limit state (from Claude Code's statusline `rate_limits`).

func LatestRateLimit added in v0.4.0

func LatestRateLimit(ctx context.Context, q Querier, window string) (RateLimitSnapshot, bool, error)

LatestRateLimit returns the current state for a window, or ok=false when none.

func RateLimitSamples added in v0.159.0

func RateLimitSamples(ctx context.Context, q Querier, window string, sinceMs int64) ([]RateLimitSnapshot, error)

RateLimitSamples is every kept sample of one plan window (the history, and the latest row, which is newer than the history's newest when the throttle skipped it), oldest first, from sinceMs on.

func RateLimitsWithPrefix added in v0.63.0

func RateLimitsWithPrefix(ctx context.Context, q Querier, prefix string) ([]RateLimitSnapshot, error)

RateLimitsWithPrefix returns every window stored under prefix, with the prefix stripped from Window.

type RateSpan added in v0.122.0

type RateSpan struct {
	CostUSD       float64 `json:"cost_usd"`
	ActiveHours   int64   `json:"active_hours"`
	ActiveCostUSD float64 `json:"active_cost_usd"`
	// Tokens is input, output, cache reads and cache writes; ActiveTokens
	// the active hours' share of it.
	Tokens       int64 `json:"tokens"`
	ActiveTokens int64 `json:"active_tokens"`
	WallHours    int64 `json:"wall_hours"`
	// Days is how many local days had an active hour (Usual only).
	Days int `json:"days,omitempty"`
}

RateSpan is a stretch of hours: what it cost, its active agent-hours and what they cost, its tokens, and how many clock hours had any priced turn at all (WallHours: the repository's wall-clock hours of work, however many agents ran in them).

type RecentDirDetail added in v0.38.0

type RecentDirDetail struct {
	Dir         string
	Sessions    int64
	LastEventAt int64
}

RecentDirDetail is a directory sessions have run in, for the folder picker.

func RecentDirs added in v0.38.0

func RecentDirs(ctx context.Context, q Querier, limit int) ([]RecentDirDetail, error)

RecentDirs lists the directories sessions have run in, most recently active first.

The repository someone wants to start in next is almost always one they were in yesterday, so this is the half of the folder picker that needs no browsing at all. Grouped by repository root where one is known and by working directory otherwise: two sessions started from different subdirectories of one repository are one entry, because they are one project to the person choosing.

"/", the home directory and a temp directory are left out (NotAProject): something on the machine running `claude` from "/" every few minutes would otherwise hold the top of the list for good.

func SessionRepoRoots added in v0.75.0

func SessionRepoRoots(ctx context.Context, q Querier) ([]RecentDirDetail, error)

SessionRepoRoots lists the repository roots sessions ran in, most recently active first — the candidates for seeding the projects list. The caller decides which are worth listing (ProjectWorthListing).

type RecentRepo added in v0.118.0

type RecentRepo struct {
	Root      string
	SessionID string
	LastAt    int64
}

RecentRepo is a repository a session worked in, and the newest such session.

func RecentRepos added in v0.118.0

func RecentRepos(ctx context.Context, q Querier, fromMs int64, limit int) ([]RecentRepo, error)

RecentRepos is the repositories sessions recorded anything in at or after fromMs, newest first, at most limit. Sessions outside a repository are not counted.

type RelayLink struct {
	SessionID string `json:"session_id"`
	Agent     string `json:"agent"`
	Title     string `json:"title,omitempty"`
	StartedAt int64  `json:"started_at"`
}

RelayLink is one end of a relay, as a session page names it.

type RemovalCandidate added in v0.73.0

type RemovalCandidate struct {
	SessionID   string  `json:"session_id"`
	Cwd         string  `json:"cwd"`
	Project     string  `json:"project"`
	Agent       string  `json:"agent"`
	Status      string  `json:"status"`
	Owned       bool    `json:"owned"`
	LastEventAt int64   `json:"last_event_at"`
	Turns       int64   `json:"turns"`
	CostUSD     float64 `json:"cost_usd"`
}

RemovalCandidate is a session as the remove commands list it: enough to tell a test run's leftovers from real work before anything is deleted.

func FindRemovalCandidates added in v0.73.0

func FindRemovalCandidates(ctx context.Context, q Querier, ids []string, cwdPrefix string) ([]RemovalCandidate, error)

FindRemovalCandidates lists the sessions named by ids, or every session whose working directory is cwdPrefix or lies under it. One of the two must be given: an empty filter matching everything is never what anyone meant.

type RepoAgents added in v0.122.0

type RepoAgents struct {
	// Days is the window the usuals are set against, today excluded.
	Days int `json:"days"`
	// Rate is what an hour of agent work costs.
	Rate RepoRate `json:"rate"`
	// Team is how many agents worked, day by day.
	Team RepoTeam `json:"team"`
}

RepoAgents is one repository's two agent figures on the Pipeline (.ai/04-ui.md § Pipeline; owner, 2026-10-15, translated: "In Pipeline I'm missing the cost of an hour of work … and roughly the size of this agent team on a chart: how many there are and were"). Both are measured here, from the repository's own sessions (rule 6); a comparison with too little history is withheld by the caller, with the day count it needs to decide.

func RepoAgentsAt added in v0.122.0

func RepoAgentsAt(ctx context.Context, q Querier, now time.Time, roots []string, past *RepoAgentsPast) (*RepoAgents, error)

RepoAgentsAt measures both figures as of now (whose location decides the days) for the sessions whose repo_root is one of roots, on top of past — measured here when nil or from another day. Two grouped scans of the covering index of priced turns (idx_events_turn_agent), one per figure, over today only.

type RepoAgentsPast added in v0.122.0

type RepoAgentsPast struct {
	// Day is the local date the cut was made on; a past from another day
	// is not used.
	Day string
	// contains filtered or unexported fields
}

RepoAgentsPast is the part of both figures before today's local midnight, which no later turn changes: the rate's hours and the team's finished days. The API keeps it for the day (pipeAgentsPastTTL), so a request scans only today — the whole window is a few times slower than the 50 ms a polled figure may take (.ai/03-contracts.md § Pipeline agents).

func RepoAgentsBefore added in v0.122.0

func RepoAgentsBefore(ctx context.Context, q Querier, now time.Time, roots []string) (*RepoAgentsPast, error)

RepoAgentsBefore measures what lies before today's local midnight.

type RepoInfo added in v0.12.2

type RepoInfo struct {
	// Root is the absolute repository root, or "" when the cwd is not inside a
	// repository.
	Root string
	// Repo is the display label for the repository row.
	Repo string
	// Path is the location within the repository, "" for the repository root
	// itself. Always slash-separated, whatever the host's separator.
	Path string
}

RepoInfo is the two-level project identity of a working directory.

func RepoFromCwd added in v0.12.2

func RepoFromCwd(cwd string) RepoInfo

RepoFromCwd resolves the repository a working directory belongs to.

It walks up from cwd looking for `.git`. A `.git` DIRECTORY is an ordinary clone. A `.git` FILE is a linked worktree — including the `.caprock-worktrees/ worker-N` trees Caprock creates for its own agents — and its `gitdir:` line points into `<parent>/.git/worktrees/<name>`, so the parent repository is recovered from it and the worker's spend lands on the repository it is actually working on, which is the whole point of a worktree.

A cwd with no repository above it (/tmp, a scratchpad) is labelled from the path itself, never given a fabricated repository name.

func (RepoInfo) Segment added in v0.12.2

func (r RepoInfo) Segment() string

Segment returns the row label for the breakdown inside a repository: the directory path under the root, written from the root so it reads as a path rather than a name — "/", "/ui", "/ui/src". Collapsing to the first segment was the first version and hid the distinction the breakdown exists to show: in a monorepo, "/services/api" and "/services/web" are the two rows anyone opening this actually wants.

type RepoRate added in v0.122.0

type RepoRate struct {
	// Last24 is the last 24 clock hours, the current one included.
	Last24 RateSpan `json:"last24"`
	// Usual is the RepoAgentDays×24 hours before Last24; absent with no
	// active hour in them.
	Usual *RateSpan `json:"usual,omitempty"`
	// Series is the previous RepoAgentDays local days, oldest first, then
	// today so far.
	Series []RateDay `json:"series"`
}

RepoRate is the repository's cost per active agent-hour. An active agent-hour is Usual's rule, the one the cockpit's burn is set against: a clock hour in which one session (its subagents included) made at least UsualMinCalls priced calls costing more than nothing. Spend in an hour below that is in CostUSD but not in the rate: a session touched in passing is not an hour anyone worked.

type RepoTeam added in v0.122.0

type RepoTeam struct {
	// Now is the agents with a turn in the last RepoAgentNowMs.
	Now TeamCount `json:"now"`
	// PeakToday is today's busiest five minutes: the most agents with a
	// turn in one bucket; zero with none today.
	PeakToday int64 `json:"peak_today"`
	// Series is the previous RepoTeamDays local days, oldest first, then
	// today so far.
	Series []TeamDay `json:"series"`
}

RepoTeam is the repository's agents as a contributors chart: every main session and every subagent (a session's agent_id) that made an assistant turn, counted once a day.

type Run added in v0.74.0

type Run struct {
	// PromptAt is the last main-thread prompt at or before the end, unix ms;
	// 0 when the session has none, and then the run is the whole session.
	PromptAt  int64
	CostUSD   float64
	ToolCalls int
	// Files are the paths edited in the run, first edited first.
	Files []string
}

Run is what a session did since its owner's last prompt, up to a moment: what a "finished" phone alert reports (ADR-036).

func LastRun added in v0.74.0

func LastRun(ctx context.Context, q Querier, sessionID string, until int64) (Run, error)

LastRun reads the run of a session that ended at until (unix ms). Subagents' turns and tool calls are counted with the session's: they are work the run paid for.

type SavedPrompt added in v0.102.0

type SavedPrompt struct {
	ID   int64  `json:"id"`
	Kind string `json:"kind"` // prompt | command
	Name string `json:"name"`
	Text string `json:"text"`
	// ProjectID is the project it belongs to; 0 means every project.
	ProjectID int64 `json:"project_id,omitempty"`
	// ProjectRoot and ProjectName are the project's, joined in when listed,
	// so a client can scope it to a folder without a second request.
	ProjectRoot string `json:"project_root,omitempty"`
	ProjectName string `json:"project_name,omitempty"`
	Sort        int64  `json:"sort"`
	CreatedAt   int64  `json:"created_at"`
	UpdatedAt   int64  `json:"updated_at"`
}

SavedPrompt is one saved prompt or command (migration 0045, ADR-051).

func GetSavedPrompt added in v0.102.0

func GetSavedPrompt(ctx context.Context, q Querier, id int64) (SavedPrompt, error)

GetSavedPrompt returns one row; ErrSavedNotFound when unknown.

func InsertSavedPrompt added in v0.102.0

func InsertSavedPrompt(ctx context.Context, q Querier, v SavedPrompt, now int64) (SavedPrompt, error)

InsertSavedPrompt adds a row and returns it as listed.

func ListSavedPrompts added in v0.102.0

func ListSavedPrompts(ctx context.Context, q Querier) ([]SavedPrompt, error)

ListSavedPrompts returns every saved prompt and command: the ones for every project first, then by project, then by sort and name.

func UpdateSavedPrompt added in v0.102.0

func UpdateSavedPrompt(ctx context.Context, q Querier, v SavedPrompt, now int64) (SavedPrompt, error)

UpdateSavedPrompt replaces a row's kind, name, text, project and sort.

type SchemaTooNewError added in v0.142.0

type SchemaTooNewError struct {
	Path     string // the database file, "" for an in-memory one
	Database int    // meta.schema_version as the newer Caprock left it
	Binary   int    // the highest migration embedded in this binary
}

SchemaTooNewError is a database that a newer Caprock has migrated past the last migration this binary carries (ADR-082). Opening it anyway is how a downgrade loses data: this binary would run its jobs — backfills, retention, cleanup, VACUUM — against tables whose shape it does not know, and nothing would say so. So the open is refused before anything is written.

func (*SchemaTooNewError) Error added in v0.142.0

func (e *SchemaTooNewError) Error() string

type Session

type Session struct {
	SessionID      string `json:"session_id"`
	Cwd            string `json:"cwd"`
	Project        string `json:"project"`
	Model          string `json:"model"`
	StartedAt      int64  `json:"started_at"`
	LastEventAt    int64  `json:"last_event_at"`
	Status         string `json:"status"` // active|idle|ended
	TranscriptPath string `json:"transcript_path"`
	HasHooks       bool   `json:"has_hooks"`
	HasTranscript  bool   `json:"has_transcript"`
	GitBranch      string `json:"git_branch"`
	Version        string `json:"version"`
	RepoRoot       string `json:"repo_root,omitempty"`
	RepoPath       string `json:"repo_path,omitempty"`
	Owned          bool   `json:"owned"`
	Worktree       string `json:"worktree,omitempty"`
	SpawnCommand   string `json:"spawn_command,omitempty"`
	PID            int    `json:"pid,omitempty"`
	ExitCode       *int   `json:"exit_code,omitempty"`
	// Agent is which coding agent produced this session. Every session was
	// Claude Code until OpenCode support, so "claude" is the default and the
	// UI treats an empty value as such.
	Agent string `json:"agent,omitempty"`
	// Title is the agent's own name for the session — Claude Code's ai-title,
	// OpenCode's title — or empty when it has not named one.
	Title string `json:"title,omitempty"`
	// Prompt is the first thing the user typed, stored only for agents whose
	// prompts are not events (Codex). The API folds it into the description.
	Prompt string `json:"-"`
	// WorkedAt is the last prompt, reply or tool call — not the exit, /clear or
	// shutdown that may have followed it (FB-037).
	WorkedAt int64 `json:"worked_at,omitempty"`
	// ParentSession is the session this one continues: the one a /clear
	// replaced, or the one it was forked from (FB-039).
	ParentSession string `json:"parent_session,omitempty"`
	// NativeID is the agent's own id for a Codex or OpenCode session Caprock
	// started under an id of its own (migration 0032); empty otherwise.
	NativeID string `json:"native_id,omitempty"`
	// RelayFrom is the session whose work this one was started to carry on,
	// with a brief rather than the conversation (migration 0036); empty
	// otherwise.
	RelayFrom string `json:"relay_from,omitempty"`
	// Subscription is the sign-in the session ran on (migration 0044,
	// ADR-048): a subscription id from Settings → Subscriptions, or empty for
	// the user's normal sign-in.
	Subscription string `json:"subscription,omitempty"`
	// SubagentModel is the model the session's subagents were started to run
	// on (migration 0065): "haiku", "sonnet" or "opus"; empty when they follow
	// the session.
	SubagentModel string `json:"subagent_model,omitempty"`
	// AttemptGroup, Attempt and Attempts say the session is attempt Attempt
	// of Attempts started together on one first message (migration 0046,
	// ADR-052); empty and zero otherwise.
	AttemptGroup string `json:"attempt_group,omitempty"`
	Attempt      int    `json:"attempt,omitempty"`
	Attempts     int    `json:"attempts,omitempty"`
	// Name is the user's own name for the session, set from its tab or
	// sidebar row (migration 0052); it outranks Title wherever a session is
	// named. Never omitted: a live frame patches the held copy, and a frame
	// without the key would leave a cleared name standing.
	Name string `json:"name"`
	// Chat marks a session Caprock started in its chats workspace
	// (<data_dir>/chats/<stamp>/) to ask something rather than to work on a
	// repository (migration 0059, ADR-071). ArchivedAt (unix ms) hides one
	// from the Chats list; 0 when it is not archived.
	Chat       bool  `json:"chat,omitempty"`
	ArchivedAt int64 `json:"archived_at,omitempty"`
	// IdleEndedAt is when Caprock ended the session because it sat idle
	// with no tab (unix ms, migration 0067), and IdleEndedAfter the idle
	// window that did it (ms); both 0 otherwise, and again once the
	// session is continued.
	IdleEndedAt    int64 `json:"idle_ended_at,omitempty"`
	IdleEndedAfter int64 `json:"idle_ended_after_ms,omitempty"`
}

Session mirrors the sessions table.

func GetSession

func GetSession(ctx context.Context, q Querier, id string) (Session, error)

GetSession returns one session; sql.ErrNoRows when unknown.

func ListOwnedActive

func ListOwnedActive(ctx context.Context, q Querier) ([]Session, error)

ListOwnedActive returns owned sessions that are not ended (for restart bookkeeping).

func ListSessions

func ListSessions(ctx context.Context, q Querier, activeOnly bool, limit int) ([]Session, error)

ListSessions returns sessions newest-first. activeOnly filters out ended.

func ListSessionsInDir added in v0.66.0

func ListSessionsInDir(ctx context.Context, q Querier, dir string, limit int) ([]Session, error)

ListSessionsInDir returns the sessions of one project row, newest-first: those whose repository root is dir, and those outside any repository whose directory is dir. It is the same grouping the Projects panel uses (see Summary: rows are keyed by repo_root, else by cwd), so "the sessions of this row" means exactly the sessions that were summed into it. Exact match, not the session search: a search also reads prompts, and "acme-api" would match every session that ever mentioned it.

func ListSessionsMatching added in v0.59.0

func ListSessionsMatching(ctx context.Context, q Querier, activeOnly bool, search string, limit int) ([]Session, error)

ListSessionsMatching returns sessions newest-first, optionally only those matching a search — see sessionQueryFilter for what a search looks at.

func ListSessionsQuery added in v0.126.0

func ListSessionsQuery(ctx context.Context, q Querier, f SessionQuery, limit int) ([]Session, error)

ListSessionsQuery returns sessions newest-first under a SessionQuery: the session list's filter plus which of the chats it holds (ADR-071).

type SessionCall added in v0.95.0

type SessionCall struct {
	ID      int64
	Ts      int64
	Model   string
	CostUSD float64
	Tokens  *event.TokenDelta
	// Tools are the tool calls this model call asked for, joined by msg_id —
	// exact, the tool_use block and the usage billed for it share the
	// message id. Empty when it asked for none or its agent records no id.
	Tools []CallTool
	// ToolCount is how many it asked for, which Tools may hold fewer of.
	ToolCount int
}

SessionCall is one priced model call of a session's main thread: what the cockpit's spend scrubber reads bar by bar.

func SessionCalls added in v0.95.0

func SessionCalls(ctx context.Context, q Querier, sessionID string, n int) ([]SessionCall, error)

SessionCalls returns the newest n priced main-thread model calls of a session, oldest first, each with the tool calls it requested. Internal model calls and unpriced turns are left out, as the cockpit's spark leaves them out; a subagent's calls are its own. Both queries pin the session's index (`+kind`), as the subagent queries do.

type SessionExit added in v0.157.0

type SessionExit struct {
	SessionID string
	Code      int
	RanMs     int64
	Early     bool
	Tail      string
	At        int64
}

SessionExit is how an owned session's program ended (migration 0072).

func GetExit added in v0.157.0

func GetExit(ctx context.Context, q Querier, id string) (SessionExit, bool, error)

GetExit is how a session ended; ok is false when nothing was recorded.

type SessionOverlap added in v0.116.0

type SessionOverlap struct {
	Checkout string        `json:"checkout"`
	With     []OverlapPeer `json:"with"`
}

SessionOverlap is one session's neighbours in its checkout.

type SessionPR added in v0.70.0

type SessionPR struct {
	SessionID string `json:"session_id"`
	URL       string `json:"url"`
	Number    int    `json:"number"`
	Title     string `json:"title,omitempty"`
	OpenedAt  int64  `json:"opened_at,omitempty"`
	// MergedAt is set only when a merge was recorded; a PR without it is not
	// known to be merged, which is not the same as known to be open.
	MergedAt int64 `json:"merged_at,omitempty"`
	ClosedAt int64 `json:"closed_at,omitempty"`
	LastAt   int64 `json:"last_at"`
}

SessionPR is a pull request a session opened or merged (migration 0035).

func SessionPRs added in v0.70.0

func SessionPRs(ctx context.Context, q Querier, sessionID string) ([]SessionPR, error)

SessionPRs lists a session's pull requests, the latest first.

type SessionPatch

type SessionPatch struct {
	Cwd, Project, Model, TranscriptPath, GitBranch, Version string
	// SubagentModel is the model of a subagent's turn inside this session. It
	// names the session only while nothing else has: a session run on Opus
	// whose Explore subagent ran on Haiku is an Opus session, and its card,
	// its list row and its context window all read this column. Model, the
	// main thread's, always wins over it.
	SubagentModel string
	// FromSubagent says Cwd, GitBranch and TranscriptPath were reported by a
	// subagent of this session. A subagent works where it was put — often a
	// git worktree of its own, on its own branch — so its place only fills a
	// session that has none yet and never overwrites the main thread's: the
	// owner's session in ~/dev/caprock on master read as a background agent's
	// `feat/…` worktree (2026-10-09).
	FromSubagent bool
	// Agent is the coding agent that produced the session ("claude",
	// "opencode"). Empty leaves the column at its default rather than
	// overwriting a value already stored.
	Agent                    string
	StartedAt, LastEventAt   int64
	FromHook, FromTranscript bool
	Status                   string // set only to force a status
	// PID is the process the session belongs to, reported by the shim. Zero
	// leaves whatever is stored alone: most events do not carry one, and an
	// event that does not know the pid must not erase one that did.
	PID int
	// Title is the agent's own name for the session. Empty leaves the stored
	// one alone.
	Title string
	// WorkedAt is set by work events only (a prompt, a reply, a tool call);
	// zero leaves the stored value. See migration 0027.
	WorkedAt int64
	// ParentSession names the session this one continues, when known; empty
	// leaves the stored one alone.
	ParentSession string
	// Subscription is the sign-in the session runs on (ADR-048). The first
	// non-empty value is kept: the spawn knows it before any event does, and
	// a session cannot move from one sign-in to another.
	Subscription string
}

SessionPatch carries the fields an event may reveal about its session. Empty strings mean "no information" and are never written over existing values.

type SessionQuery added in v0.126.0

type SessionQuery struct {
	Active bool   // leave out ended sessions
	Search string // see sessionQueryFilter
	Chats  ChatScope
	// Archived, with ChatsOnly, lists the archived chats instead of the
	// others.
	Archived bool
}

SessionQuery is what the session list is filtered by.

type SliceSize added in v0.64.0

type SliceSize struct {
	Name         string `json:"name"`
	Events       int64  `json:"events"`
	PayloadBytes int64  `json:"payload_bytes"`
}

SliceSize is one group of events.

type Spark added in v0.13.0

type Spark struct {
	FromMs      int64     `json:"from_ms"`
	WidthMs     int64     `json:"width_ms"`
	Cost        []float64 `json:"cost"`
	Tokens      []int64   `json:"tokens"`
	Input       []int64   `json:"input"`
	Turns       []int64   `json:"turns"`
	ActiveHours []int64   `json:"active_hours"`
	ActiveCost  []float64 `json:"active_cost"`
}

Spark is a project's spend over time, as one value per fixed-width bucket — the series behind the sparkline on the Projects panel. It answers "when did this repo cost that" without shipping the events themselves.

Cost and tokens travel together, as two parallel arrays over the SAME buckets, because which of the two the panel plots stays a display choice on the client. Sending only one of them would make re-basing the picture a network round trip — on a polled endpoint, a control that stalls — and sending events so the client could bucket them itself would be orders of magnitude more payload for a picture 120px wide.

Bucket i covers [FromMs + i*WidthMs, FromMs + (i+1)*WidthMs). The last bucket is the one containing "now" and is therefore still filling; it is not extrapolated to a full bucket's worth (rule 6).

Input and Turns are two more parallel arrays from the same scan, for the cockpit's spend chart, which can plot the period by either of them as well as by cost: Input is the input side of Tokens (fresh input plus cache reads and writes, the cockpit's own "tokens"), and Turns the assistant turns, the summary's own `turns` counted per bucket.

ActiveHours and ActiveCost are the burn rate's, per bucket, from the same scan: how many active session-hours fell in the bucket — clock hours in which one session made at least UsualMinCalls priced calls costing more than nothing, the very hours Usual's burn is the median of — and what those hours cost. ActiveCost / ActiveHours is the bucket's dollars per active hour, so idle time does not water it down, and a bucket with no active hour has no rate at all rather than $0/h.

type SparkSpec added in v0.13.0

type SparkSpec struct {
	// Buckets is how many columns the panel will paint.
	Buckets int
	// WidthMs is one column's width. Callers derive it from the selected range
	// (a day for 30d/7d, an hour for today) so the picture and the number beside
	// it always describe the same period.
	WidthMs int64
	// FromMs is the first bucket's left edge. It is passed separately from
	// Summarize's own fromMs because a range is calendar-aligned: "30d" starts
	// at local midnight 29 days ago, and bucketing from an arbitrary instant
	// would smear each day across two columns.
	FromMs int64
}

SparkSpec asks Summarize for per-project time series. Buckets <= 0 disables them entirely, which is the default: /v1/stats/summary computes a second summary for the 10-minute burn figure, and that one has no sparkline to draw.

type SpendPart added in v0.159.0

type SpendPart struct {
	Agent        string  `json:"agent"`
	Subscription string  `json:"subscription"`
	CostUSD      float64 `json:"cost_usd"`
}

SpendPart is the share of a cost that ran on one sign-in: an agent and the subscription its sessions recorded ("" the user's own sign-in, ADR-048). A figure carries its parts so a plan figure can be priced by the plan each part ran on (internal/planshare): a pull request worked on from two subscriptions is two parts, each at its own plan's rate.

type SpendParts added in v0.159.0

type SpendParts []SpendPart

SpendParts is a cost split by sign-in, at most one entry per (agent, subscription), dearest first once Sorted.

func SpendPartsBetween added in v0.159.0

func SpendPartsBetween(ctx context.Context, q Querier, fromMs, toMs int64, agent AgentFilter) (SpendParts, error)

SpendPartsBetween is the priced work in [fromMs, toMs) by agent and subscription — the Cost screen's total split by sign-in, and the plan figures' denominators (internal/planshare). toMs <= 0 means no upper bound. Every kind's cost counts, internal turns excepted, the same scope as the summary's cost_usd; spend whose session row is gone is the own sign-in's Claude Code, which is what a session recorded before ADR-048 was.

One covering range scan (idx_events_ts_cover) joined to sessions: 0.5 s for 30 days and 1.0 s for all time on a 2.2 GB copy of the owner's database, in the sqlite shell (2026-10-25), so its callers cache it.

func (SpendParts) Add added in v0.159.0

func (p SpendParts) Add(agent, subscription string, cost float64) SpendParts

Add puts cost on (agent, subscription), and returns the parts. A zero or negative cost changes nothing.

func (SpendParts) Merge added in v0.159.0

func (p SpendParts) Merge(o SpendParts) SpendParts

Merge adds every part of o, and returns the parts.

func (SpendParts) Sorted added in v0.159.0

func (p SpendParts) Sorted() SpendParts

Sorted orders the parts dearest first (then by agent and subscription, so an answer is stable), in place, and returns them.

type Stats

type Stats struct {
	SessionID    string  `json:"session_id"`
	Turns        int64   `json:"turns"`
	ToolCalls    int64   `json:"tool_calls"`
	FilesTouched int64   `json:"files_touched"`
	TokensIn     int64   `json:"tokens_in"`
	TokensOut    int64   `json:"tokens_out"`
	CacheRead    int64   `json:"cache_read"`
	CacheWrite   int64   `json:"cache_write"`
	CostUSD      float64 `json:"cost_usd"`
}

Stats mirrors session_stats.

func AddStats

func AddStats(ctx context.Context, q Querier, d Stats) (Stats, error)

AddStats increments session_stats by the delta and returns the new totals.

func GetStats

func GetStats(ctx context.Context, q Querier, sessionID string) (Stats, error)

GetStats returns session_stats for a session (zeros when absent).

type Storage added in v0.64.0

type Storage struct {
	PageSize  int64 `json:"page_size"`
	PageCount int64 `json:"page_count"`
	// FreePages is the freelist: pages the file holds but no table uses. They
	// are reused by new rows before the file grows, and only VACUUM returns
	// them to the disk.
	FreePages int64 `json:"free_pages"`
	// Tables is every table with its own pages and its indexes' pages, largest
	// first. Absent when this SQLite build has no dbstat.
	Tables []TableSize `json:"tables,omitempty"`
	// Events and PayloadBytes count the events table: rows, and the bytes of
	// the raw JSON each row keeps.
	Events       int64 `json:"events"`
	PayloadBytes int64 `json:"payload_bytes"`
	// OldestTs is the oldest event's time, unix ms; 0 when there are none.
	OldestTs int64 `json:"oldest_ts"`
	// Agents and Kinds split the events by who produced them and what they
	// are, largest payload first.
	Agents []SliceSize `json:"agents"`
	Kinds  []SliceSize `json:"kinds"`
	// Recent is what the last 7 and 30 days added; Older is what is older than
	// 30 and 90 days — what a retention setting of that length would delete.
	Recent []WindowSize `json:"recent"`
	Older  []WindowSize `json:"older"`
}

Storage is what the database is made of: how many pages it has, how many of them are free, which tables and indexes hold the rest, and what the events table — nearly all of it — records.

Every figure is counted, not modelled. The one derived number, the growth estimate, is labelled as such by the caller.

Expensive by design: dbstat walks every page of the file and the events breakdown reads every row. On an 857 MB database the two took seconds, so the daemon computes this in the background and serves a cached copy; nothing on a request path may call it.

func MeasureStorage added in v0.64.0

func MeasureStorage(ctx context.Context, db *sql.DB, now time.Time) (Storage, error)

MeasureStorage reads the database's composition. See Storage for its cost.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store wraps the database handle.

func Open

func Open(ctx context.Context, path string, log *slog.Logger) (*Store, error)

func (*Store) AutoVacuum added in v0.114.0

func (s *Store) AutoVacuum(ctx context.Context) (int, error)

AutoVacuum is the database's auto_vacuum mode: 0 NONE, 1 FULL, 2 INCREMENTAL.

func (*Store) CheckpointTruncate added in v0.114.0

func (s *Store) CheckpointTruncate(ctx context.Context) (busy int64, err error)

CheckpointTruncate folds the write-ahead log back into the database and truncates it. busy is non-zero when a running read kept part of it.

func (*Store) Close

func (s *Store) Close() error

Close closes the database.

func (*Store) CompactPayloadsStep added in v0.114.0

func (s *Store) CompactPayloadsStep(ctx context.Context, window int) (CompactStep, error)

CompactPayloadsStep examines the next window of up to `window` event ids and replaces the base64 in each row that holds any (event.StripBinary). It is idempotent and resumable: the cursor moves in the transaction that rewrites the rows, and a row rewritten twice is not changed the second time.

The window is read outside the write transaction, so the write lock is held only for the updates. A row whose payload changed between the read and the write (an assistant turn whose prose was merged into it) is left for what it now holds: the update matches the payload it read, byte for byte.

func (*Store) DB

func (s *Store) DB() *sql.DB

DB exposes the raw handle for packages that need transactions (rollup).

func (*Store) EnableIncrementalVacuum added in v0.114.0

func (s *Store) EnableIncrementalVacuum(ctx context.Context) error

EnableIncrementalVacuum sets auto_vacuum=INCREMENTAL and runs the VACUUM that makes it take effect, which also gives every free page back. Both statements go to one connection: the mode is that connection's request to its next VACUUM.

VACUUM copies the database to a temporary file and writes it back through the write-ahead log, holding the write lock throughout; the caller decides when that is affordable. Cancelling ctx interrupts it, and an interrupted VACUUM rolls back and leaves the database as it was.

func (*Store) FillToolFields added in v0.151.0

func (s *Store) FillToolFields(ctx context.Context, window int, pause time.Duration) (int, error)

FillToolFields runs ToolFieldsStep until nothing is pending, resting between steps so ingest and the dashboard always find the database free.

func (*Store) GetMeta

func (s *Store) GetMeta(ctx context.Context, key string) (string, error)

GetMeta reads a meta value; "" when absent.

func (*Store) IncrementalVacuum added in v0.114.0

func (s *Store) IncrementalVacuum(ctx context.Context, n int) (int64, error)

IncrementalVacuum returns up to n free pages to the disk and says how many it returned. On a database not in INCREMENTAL mode it does nothing.

func (*Store) Pages added in v0.114.0

func (s *Store) Pages(ctx context.Context) (PageCounts, error)

Pages reads the page size, the page count and the freelist.

func (*Store) PayloadCompactFinished added in v0.114.0

func (s *Store) PayloadCompactFinished(ctx context.Context) (bool, error)

PayloadCompactFinished reports whether the payload compaction has finished.

func (*Store) SchemaVersion

func (s *Store) SchemaVersion(ctx context.Context) (int, error)

SchemaVersion returns the applied schema version (0 = empty database).

func (*Store) SetMeta

func (s *Store) SetMeta(ctx context.Context, key, value string) error

SetMeta upserts a meta value.

func (*Store) ToolFieldsStep added in v0.151.0

func (s *Store) ToolFieldsStep(ctx context.Context, window int) (filled int, done bool, err error)

ToolFieldsStep fills the fields of up to window pending event ids, the newest first, and moves the pending mark below them in the same transaction: an interrupted pass resumes where it stopped, and a reader never sees a row as filled before it is. Done when nothing is pending.

func (*Store) UpsertGitHubPRs added in v0.153.0

func (s *Store) UpsertGitHubPRs(ctx context.Context, repo string, prs []GitHubPR, seenAt int64) error

UpsertGitHubPRs keeps the headers of a pull request list just read for repo ("owner/name") in github_prs, seen at seenAt (unix ms). A row is rewritten only by a read at least as new as the one it holds (GitHub's updated_at), so an older list read late never undoes a newer one. One transaction, idempotent.

func (*Store) WithTx

func (s *Store) WithTx(ctx context.Context, fn func(q Querier) error) error

WithTx runs fn inside a transaction, committing on nil error.

type SubagentActivity added in v0.92.0

type SubagentActivity struct {
	AgentID string
	// AgentType is the hook's agent_type ("general-purpose", "Explore"); empty
	// when no hook named one.
	AgentType string
	// Description is what the parent asked it to do, from the Agent call
	// that launched it, when its result names the agent (a background launch
	// does at once; a foreground one only when it finishes).
	Description string
	// ToolCalls is how many tool calls it has made in all.
	ToolCalls int
	// StartedAt and LastAt are its first and newest events in the window, unix ms.
	StartedAt, LastAt int64
	// Tool, Input and ToolAt are its newest call; empty when it made none.
	Tool   string
	Input  json.RawMessage
	ToolAt int64
	// Running is true while that call has no result.
	Running bool
	// StoppedAt is its SubagentStop (unix ms), for one that finished.
	StoppedAt int64
	// Asking is true when its newest event is a permission prompt: a
	// subagent waiting on a dialog records nothing else.
	Asking bool
}

SubagentActivity is one subagent working in a session now: who it is and what it is doing, read from the hooks fired inside it (they carry its agent_id) — Claude Code sends no event when a subagent starts.

func SubagentsDone added in v0.94.0

func SubagentsDone(ctx context.Context, q Querier, sessionID string, since int64, limit int) ([]SubagentActivity, error)

SubagentsDone returns up to limit subagents of a session that stopped since `since` after making at least one tool call, newest stop first: the ones SubagentsNow counts as finished. StoppedAt is their SubagentStop.

func SubagentsNow added in v0.92.0

func SubagentsNow(ctx context.Context, q Querier, sessionID string, since int64) ([]SubagentActivity, int, error)

SubagentsNow returns the subagents working in a session — each agent id heard from since `since` whose newest event is not its SubagentStop, the rule LiveSubagents counts by — newest activity first, and how many stopped within the window after making at least one tool call. Claude Code also fires SubagentStop for small internal agents that run no tools; they are not counted.

type SubagentCall added in v0.110.0

type SubagentCall struct {
	// ID is the call's tool.pre event id: the cursor "show earlier" pages by.
	ID        int64
	ToolUseID string
	Tool      string
	Input     json.RawMessage
	StartedAt int64
	// EndedAt is its result's time; 0 while it has none.
	EndedAt int64
	// Error is true when the result came back as an error.
	Error bool
}

SubagentCall is one tool call a subagent made, joined to its result.

type SubagentSpend added in v0.94.0

type SubagentSpend struct {
	// Model is its newest turn's model; empty when it has none yet.
	Model string
	// CostUSD sums its turns' costs. Known is false when it has no turn, or
	// a turn the pricing table could not price: a partial sum would
	// understate it, and no figure is better than a wrong one (rule 6).
	CostUSD float64
	Known   bool
}

SubagentSpend is what a subagent's own model calls cost, from its transcript's turns (each carries its model and usage, and is priced like any other turn).

func SubagentsSpend added in v0.94.0

func SubagentsSpend(ctx context.Context, q Querier, sessionID string) (map[string]SubagentSpend, SubagentSpend, error)

SubagentsSpend returns each subagent's spend in a session, keyed by agent id, and the total over all of them, Known only when every one is. Internal model calls are left out, as every total leaves them out.

type SubagentToolSpend added in v0.110.0

type SubagentToolSpend struct {
	Tool    string
	Calls   int
	CostUSD float64
	Known   bool
}

SubagentToolSpend is what one kind of tool cost inside a subagent: the turns that called it, each turn's cost split evenly over the tools it called. Calls counts the calls; Known is false when any of those turns could not be priced.

type SubagentTrail added in v0.110.0

type SubagentTrail struct {
	AgentID   string
	AgentType string
	// Description, Prompt and SubagentType are the parent's Agent/Task call
	// input; ParentToolUseID that call's id. Empty when no call is linked.
	Description     string
	Prompt          string
	SubagentType    string
	ParentToolUseID string
	// Background is true when the parent launched it in the background.
	Background bool
	// StartedAt and LastAt are its first and newest events, StoppedAt its
	// newest SubagentStop when that is its newest event (unix ms).
	StartedAt, LastAt, StoppedAt int64
	// Result is the text it returned: its SubagentStop's last message, else
	// the parent call's result.
	Result string
	// Calls is every call, oldest first.
	Calls []SubagentCall
	// Asking is true while its newest event is a permission prompt.
	Asking bool
	// Turn figures: its own model calls, internal ones left out.
	Turns                                      int
	TokensIn, TokensOut, CacheRead, CacheWrite int64
	CostUSD                                    float64
	CostKnown                                  bool
	Model                                      string
	ByTool                                     []SubagentToolSpend
}

SubagentTrail is everything Caprock holds about one subagent of a session: the task its parent gave it, its calls in order, what it answered, and its numbers. Read in two scans of the session's rows (idx_events_session_ts), so a parent with thousands of events is not paged through.

func SubagentTrailOf added in v0.110.0

func SubagentTrailOf(ctx context.Context, q Querier, sessionID, agentID string) (tr SubagentTrail, found bool, err error)

SubagentTrailOf reads one subagent of a session. found is false when the session holds no event of that agent.

type SubscriptionSpend added in v0.101.0

type SubscriptionSpend struct {
	Agent        string
	Subscription string // "" is the Default sign-in
	Sessions     int64
	CostUSD      float64
}

SubscriptionSpend is one subscription's work since a moment (ADR-048).

func SpendBySubscription added in v0.101.0

func SpendBySubscription(ctx context.Context, q Querier, since int64) ([]SubscriptionSpend, error)

SpendBySubscription sums the priced turns since `since` (unix ms) per agent and subscription, for Settings → Subscriptions. Only agents that have subscriptions are asked for; internal turns (the agent's own housekeeping calls) are left out, as everywhere else a cost is shown.

type Summary

type Summary struct {
	Range      string         `json:"range"`
	FromMs     int64          `json:"from_ms"`
	Sessions   int64          `json:"sessions"`
	Active     int64          `json:"active_sessions"`
	Turns      int64          `json:"turns"`
	ToolCalls  int64          `json:"tool_calls"`
	TokensIn   int64          `json:"tokens_in"`
	TokensOut  int64          `json:"tokens_out"`
	CacheRead  int64          `json:"cache_read"`
	CacheWrite int64          `json:"cache_write"`
	CostUSD    float64        `json:"cost_usd"`
	Models     []ModelShare   `json:"models"`
	Projects   []ProjectShare `json:"projects"`
	// Work is what the money was spent ON — the breakdown by the KIND of work
	// each turn did, beside the cuts by model and by project. Rows sum exactly
	// to CostUSD and Tokens; see workkind.go for the rule.
	Work []WorkShare `json:"work"`
	// WorkUnlinkedCalls is how many tool calls in the range could not be
	// attached to any turn, so their cost was counted in the "no tool" row
	// rather than in the row for the work they actually did.
	//
	// It exists because the failure is INVISIBLE otherwise: an unlinked call
	// leaves its turn looking exactly like a turn that genuinely called
	// nothing, so a broken linkage quietly inflates "no tool" and understates
	// every other row. Publishing the breakdown without publishing this would
	// be publishing a number we know might be wrong (rule 6). The UI says so
	// whenever it is non-zero, and `caprock report` withholds the breakdown
	// entirely when the share is large enough to change the ranking.
	WorkUnlinkedCalls int64 `json:"work_unlinked_calls"`
	// Unpriced is the volume in this range whose model is not in the pricing
	// table, so it contributes nothing to CostUSD. Omitted when everything was
	// priced. Without it the aggregates flattened unknown models into the
	// COALESCE(SUM(cost_usd),0) total and 61k tokens of a model shipped after
	// the pricing table rendered as a confident "$0.00" — indistinguishable
	// from free, and an invented number under rule 6.
	Unpriced *Unpriced `json:"unpriced,omitempty"`
	// Background is measured token usage from known internal product machinery,
	// kept outside user session/turn/cost totals. It is not an error and carries
	// no invented dollar value when its vendor publishes none.
	Background *BackgroundUsage `json:"background,omitempty"`
	// Hermes is Hermes Agent's spend in the range, split by what kind of
	// figure it is and by background work (ADR-069). Already inside CostUSD;
	// omitted when the range has no Hermes turns or another agent is
	// filtered for.
	Hermes *HermesCost `json:"hermes,omitempty"`
	// CostParts splits CostUSD by the sign-in each session ran on (agent and
	// subscription), for the plan figures (internal/planshare). Filled by the
	// API's range summary, not by SummarizeSparkFor.
	CostParts SpendParts `json:"cost_parts,omitempty"`
}

Summary is the aggregate for /v1/stats/summary.

func RecentSpend added in v0.116.0

func RecentSpend(ctx context.Context, q Querier, fromMs int64, agent AgentFilter) (Summary, error)

RecentSpend is what was spent since fromMs — cost, tokens, turns and tool calls, and nothing else of a Summary. The Cost screen's burn tile reads the last ten minutes on every summary request; it called SummarizeSparkFor, which also counts the model mix, the projects and every turn's directory, for four figures (2026-10-14).

func Summarize

func Summarize(ctx context.Context, q Querier, fromMs int64) (Summary, error)

Summarize aggregates events since fromMs (0 = all time).

func SummarizeSpark added in v0.13.0

func SummarizeSpark(ctx context.Context, q Querier, fromMs int64, spark SparkSpec) (Summary, error)

func SummarizeSparkFor added in v0.22.0

func SummarizeSparkFor(ctx context.Context, q Querier, fromMs int64, spark SparkSpec, agent AgentFilter) (Summary, error)

SummarizeSparkFor is SummarizeSpark restricted to one agent.

type TableSize added in v0.64.0

type TableSize struct {
	Name       string `json:"name"`
	DataBytes  int64  `json:"data_bytes"`
	IndexBytes int64  `json:"index_bytes"`
}

TableSize is one table's footprint on disk.

type TaskRow

type TaskRow struct {
	ID           string  `json:"id"`
	Title        string  `json:"title"`
	Status       string  `json:"status"`
	Assignee     string  `json:"assignee"`
	BudgetUSD    float64 `json:"budget_usd"`
	VerifyRounds int     `json:"verify_rounds"`
	CostUSD      float64 `json:"cost_usd"`
	CreatedAt    int64   `json:"created_at"`
	UpdatedAt    int64   `json:"updated_at"`
}

TaskRow mirrors the tasks table (a query cache over the hive's task files).

func GetTask

func GetTask(ctx context.Context, q Querier, id string) (TaskRow, error)

GetTask returns one task row.

func ListTasks

func ListTasks(ctx context.Context, q Querier) ([]TaskRow, error)

ListTasks returns all task rows ordered by creation.

type TaskSession added in v0.15.0

type TaskSession struct {
	SessionID string `json:"session_id"`
	Cwd       string `json:"cwd"`
	FromTs    int64  `json:"from_ts"`
	ToTs      int64  `json:"to_ts,omitempty"`
}

TaskSession is one session that worked a task, newest window first. It is how the UI gets from a task card to the diff endpoint: the diff is keyed on a session id, and the board only ever knew the hive agent id.

func TaskSessions added in v0.15.0

func TaskSessions(ctx context.Context, q Querier, taskID string) ([]TaskSession, error)

TaskSessions returns the sessions attributed to a task, newest window first.

type TaxCall added in v0.56.0

type TaxCall struct {
	Ts      time.Time
	Tool    string
	Context int64
	Result  int64
	Model   string
}

TaxCall is one tool call priced against the turn that issued it: the context that turn re-read, and what the turn produced.

The link is exact, not reconstructed. A tool.pre event carries the msg_id of the assistant message whose usage was billed, so a call's context is that turn's own reading. Nearest-preceding-turn guessing recovers 38.7% of these correctly (see internal/ingest/parser.go), which is why it is not attempted.

func LoopTaxCalls added in v0.56.0

func LoopTaxCalls(ctx context.Context, q Querier, sessionID string, from, to time.Time) ([]TaxCall, int, error)

LoopTaxCalls returns the tool calls of one session in a time window, each carrying the context of the turn that issued it.

It exists to price a loop alert: the detector knows which calls repeated but stores no tokens, and the tax of a series is the sum of exactly these contexts. Calls whose turn carried no usage come back with Context 0 and are the caller's to drop -- a call that cannot be priced must not be priced as free. It also returns how many calls in the window carried no message id and so could not be attached to any turn. They are not a defect: a tool call arriving on the hook plane has no message id to carry, and 13% of all calls on the owner's archive are of that kind. But a tax summed over 87% of a loop's calls is an understatement, and an understatement nobody is told about is an invented number (rule 6). The caller reports the shortfall rather than presenting a partial figure as complete.

type TeamCount added in v0.122.0

type TeamCount struct {
	Sessions  int64 `json:"sessions"`
	Subagents int64 `json:"subagents"`
}

TeamCount is a count of main sessions and subagents.

type TeamDay added in v0.122.0

type TeamDay struct {
	Day string `json:"day"`
	TeamCount
	ByKind map[string]TeamCount `json:"by_kind,omitempty"`
	// Peak is the most agents with a turn in one five-minute bucket.
	Peak int64 `json:"peak"`
}

TeamDay is one local day's distinct agents, by agent kind (claude, codex, opencode, gemini, …), and its busiest five minutes.

type TodoItem added in v0.108.0

type TodoItem struct {
	ID         string `json:"id"`
	Text       string `json:"text"`
	Status     string `json:"status"` // pending | in_progress | completed | cancelled
	ActiveForm string `json:"active_form,omitempty"`
}

TodoItem is one entry of the task list an agent keeps for itself: Claude Code's TodoWrite and TaskCreate/TaskUpdate, OpenCode's todowrite (stored as TodoWrite) and Codex's update_plan.

type TodoList added in v0.108.0

type TodoList struct {
	Items     []TodoItem `json:"items"`
	UpdatedAt int64      `json:"updated_at"`
}

TodoList is a session's current task list and when it last changed (unix ms; 0 when the session never kept one).

func SessionTodos added in v0.108.0

func SessionTodos(ctx context.Context, q Querier, sessionID string) (TodoList, error)

SessionTodos rebuilds a session's task list from its own task tool calls. A TodoWrite or update_plan call carries the whole list, so the newest one is the list. TaskCreate adds one task and TaskUpdate changes one by id; Claude Code numbers tasks 1, 2, 3 in the order they were created within the session ("Task #3 created successfully"), so the fold numbers them the same way. Whichever of the two kinds changed last is the answer. Only the main thread counts: a subagent keeps its own list. A call recorded on both the hook and the transcript plane is folded once, by tool_use_id.

The query pins idx_events_todo (migration 0066), a partial index of these calls alone, so only they are read. Through idx_events_attr_work, which holds session_id, ts, kind and tool, it walked the session's whole index range: 4,820 page reads for the owner's largest session (180k events, no task calls) against 10 (F18, docs/resource-usage-audit-2026-10-18.md). The tool names are written into the statement, not bound: SQLite uses a partial index only when it can see the query's WHERE implies the index's.

type ToolCount

type ToolCount struct {
	Tool  string `json:"tool"`
	Count int64  `json:"count"`
	// Bytes is how much this tool handed back, summed. Not tokens: a tool
	// spends none — the turn that reads its output does — and splitting a
	// turn's tokens between its calls would put a figure on screen that looks
	// measured and is not. This is the size of what came back, which is
	// measured exactly and answers what the call count cannot: on one machine
	// Bash was called 22x more often than Read and returned a quarter as much.
	Bytes int64 `json:"bytes"`
}

ToolCount is one row of the tool-usage distribution.

func ToolDistribution

func ToolDistribution(ctx context.Context, q Querier, fromMs int64, limit int) ([]ToolCount, error)

ToolDistribution counts tool.pre events by tool since fromMs (0 = all time).

type ToolDrill added in v0.70.0

type ToolDrill struct {
	Tool string `json:"tool"`
	// Kind is how the calls are grouped: shell, files, web, mcp or other.
	Kind string `json:"kind"`
	// GroupBy names a row's key in words: command, file, domain, query,
	// action, pattern, subagent, or call.
	GroupBy string `json:"group_by"`
	// Calls is every call of the tool in the window; rows hold the top ones.
	Calls int64 `json:"calls"`
	// Results is how many of them have a recorded result, the denominator of
	// every failure rate.
	Results  int64      `json:"results,omitempty"`
	Failures int64      `json:"failures,omitempty"`
	Bytes    int64      `json:"bytes,omitempty"`
	Rows     []DrillRow `json:"rows"`
	// Other is the calls in groups below the top rows.
	Other int64 `json:"other"`
	// TrendFromMs and TrendWidthMs place each row's Trend buckets.
	TrendFromMs  int64 `json:"trend_from_ms,omitempty"`
	TrendWidthMs int64 `json:"trend_width_ms,omitempty"`
	// Hints are measured facts worth acting on, strongest first.
	Hints []DrillHint `json:"hints,omitempty"`
}

ToolDrill is what one tool did in a window: its calls grouped by what they were about (the command a shell call ran, the file a Read or Edit touched, the domain a fetch reached), with what came back and how often it failed.

Every figure is counted from stored events. Nothing is estimated: a call whose result was never recorded counts as a call and is left out of the failure rate rather than guessed at.

func ToolDrillStats added in v0.70.0

func ToolDrillStats(ctx context.Context, q Querier, o DrillOptions) (ToolDrill, error)

ToolDrillStats groups one tool's calls. The pre's group and the post's failure are read from tool_fields, stored when each was written (migration 0070), so no payload is opened; the post is found through the unique (session_id, key) index rather than by scanning results. A call stored before tool_fields and not yet filled (toolFieldsPending) is read from its payload, as every call once was, so the screen is the same either way.

type TouchDirs added in v0.14.0

type TouchDirs struct {
	// Dir is the absolute, normalized directory carried into this turn — the
	// directory of the most recent touch at or before it in the same session.
	// It is "" when no touch preceded the turn in its session (the session's
	// opening turns), which is the one case carry-forward cannot place.
	Dir string
	// HasDir distinguishes "no touch preceded this turn" from a directory that
	// normalized to the empty string, so the caller never treats the two alike.
	HasDir bool
}

TouchDirs is what one turn's attribution is decided from: the directory carried into it by the most recent file touch in its session.

type TrendBurn added in v0.117.2

type TrendBurn struct {
	// MedianUSDPerHour is the median window's spend, as dollars per hour.
	MedianUSDPerHour float64 `json:"median_usd_per_hour"`
	// Windows and Days are the samples behind it.
	Windows int `json:"windows"`
	Days    int `json:"days"`
}

TrendBurn is the median burn of the active windows in the previous Days.

type TrendDay added in v0.117.2

type TrendDay struct {
	// Day is the local date, YYYY-MM-DD.
	Day       string  `json:"day"`
	CostUSD   float64 `json:"cost_usd"`
	Sessions  int64   `json:"sessions"`
	Turns     int64   `json:"turns"`
	ToolCalls int64   `json:"tool_calls"`
	// HitRate is the cache hit rate, 0..1; absent with no input at all.
	HitRate *float64 `json:"hit_rate,omitempty"`
	// BurnUSDPerHour is the median of the day's active burn windows (whole
	// day, not cut: a rate is not a running total); absent with none.
	BurnUSDPerHour *float64 `json:"burn_usd_per_hour,omitempty"`
	// Active: any priced turn on the day, at any hour. Only active days make
	// a median — a weekend off is not a "usual" of zero.
	Active bool `json:"active"`
}

TrendDay is one local day's figures up to the cut.

type TrendModel added in v0.132.0

type TrendModel struct {
	ModelTokens
	CostUSD float64
}

TrendModel is one model's stored cost and tokens by type in a window.

type TrendWindow added in v0.132.0

type TrendWindow struct {
	Models []TrendModel
	Tools  map[string]int64
}

TrendWindow is what one window of the At a glance trend holds: each model's stored cost and tokens by type (priced into the bill by the caller), and tool calls by tool. The agents come from AgentSplit over the same bounds.

func TrendWindows added in v0.132.0

func TrendWindows(ctx context.Context, q Querier, from, cut int64) (prior, recent TrendWindow, err error)

TrendWindows splits [from, now) at cut into two windows, prior = [from, cut) and recent = [cut, now), with one grouped query for the turns and one for the tool calls: the window is a GROUP BY column, so the two windows cost one range scan each, on the same covering indexes the all-time figures read (idx_events_turn_agent, idx_events_tool_dist).

type Trends struct {
	// Days is the window behind the comparison, today excluded.
	Days int `json:"days"`
	// CutMin is the time of day, in minutes after local midnight, at which
	// every day's figures are cut: "by this time on each day". Comparing a
	// morning's spend with whole days made every morning read low.
	CutMin int `json:"cut_min"`
	// Series is the previous Days days, oldest first, then today so far.
	Series []TrendDay `json:"series"`
	// Burn is the typical burn rate when something is running.
	Burn *TrendBurn `json:"burn,omitempty"`
}

Trends is what the Now screen's Today cells are set against: the same figures for each of the previous TrendDays, cut at the same time of day, and the viewer's typical burn rate (owner, 2026-10-14, translated: "I see the number but don't understand whether it's average or above average"). Every figure is measured on this machine (rule 6); a comparison with too little history is left to the caller to withhold, with the active-day count it needs to decide.

func TrendsAt added in v0.117.2

func TrendsAt(ctx context.Context, q Querier, now time.Time, agent AgentFilter) (*Trends, error)

TrendsAt measures the trends as of now (whose location decides the days), through the agent filter. One grouped range scan of the covering index the summary already uses (idx_events_ts_cover), by (5-minute bucket, session, kind): on a copy of the owner's 1.6 GB database, 15 days (200k events, 10k groups), 0.14s in the sqlite shell and 0.28s warm through the Go driver (2026-10-14), which is why the API caches it. The rollups cannot answer this: daily_stats has no time of day, no turn or tool counts, and no agent.

type Turn added in v0.110.0

type Turn struct {
	SessionID string
	// PromptID is the turn.user event's id, to read its prompt.
	PromptID int64
	Start    int64 // unix ms
	End      int64 // unix ms; 0 while it runs
	// Failed: it ended on a StopFailure.
	Failed bool
}

Turn is one finished turn, or the open one (End 0).

func ProjectTurns added in v0.110.0

func ProjectTurns(ctx context.Context, q Querier, dir string, since time.Time, limit int) ([]Turn, error)

ProjectTurns returns the newest limit finished turns of the Claude Code sessions in one project — the repository root, else the folder, as Cost groups them — that ended at or after since, oldest first.

func SessionTurns added in v0.110.0

func SessionTurns(ctx context.Context, q Querier, ids []string, since time.Time, lookback time.Duration) ([]Turn, map[string]Turn, error)

SessionTurns returns the given sessions' turns that ended at or after since, oldest first, and each one's open turn, read from lookback before since so a turn that started earlier is whole.

func (Turn) Duration added in v0.110.0

func (t Turn) Duration() time.Duration

Duration is the finished turn's length.

type Unpriced added in v0.16.0

type Unpriced struct {
	Turns  int64 `json:"turns"`
	Tokens int64 `json:"tokens"`
	// Models are the distinct model ids with no pricing row, most volume first.
	// An empty model id (a turn recorded before its model was known) is
	// reported as "" and rendered by the UI as "unknown".
	Models []string `json:"models"`
}

Unpriced is the volume that could not be priced, and which models caused it. Naming the models matters: a user who sees an unknown model id can report it (or add a pricing override); "some tokens are unpriced" is not actionable.

type Usual added in v0.114.0

type Usual struct {
	// Days is the window the figures cover.
	Days int `json:"days"`
	// Burn is dollars per active session-hour: every clock hour in which
	// one session made at least UsualMinCalls priced calls costing more
	// than nothing, its spend in that hour. A session's hour, not the
	// machine's: four sessions at once are not one burning four times as
	// fast.
	Burn *Deciles `json:"burn,omitempty"`
	// Cost and Tokens are every session's total over the window (tokens:
	// input with cache reads and writes, as the cockpit counts them).
	Cost   *Deciles `json:"cost,omitempty"`
	Tokens *Deciles `json:"tokens,omitempty"`
	// Cache is the window's cache hit rate, 0..100; nil with no input.
	Cache *float64 `json:"cache,omitempty"`
}

Usual is what this machine's own history says is typical, so the cockpit can set a session's headline against it ("▲ 38%"). Every figure is measured here over the last UsualDays; nothing comes from elsewhere (rule 6). A distribution with too few samples is left out rather than drawn from a handful: a new user sees nothing, never a guess.

func UsualSince added in v0.114.0

func UsualSince(ctx context.Context, q Querier, fromMs int64, agent AgentFilter) (*Usual, error)

UsualSince measures the usual from fromMs on, through the agent filter. One grouped scan of the priced assistant turns, per (session, clock hour), off the covering index the summary already uses (idx_events_turn_agent): on the owner's 1.7 GB copy, 0.02s warm and 0.12s cold for 30 days (2026-10-13). Session totals are the same rows summed in Go.

type VerificationRow added in v0.15.0

type VerificationRow struct {
	Round      int    `json:"round"`
	Command    string `json:"command"`
	ExitCode   int    `json:"exit_code"`
	OutputPath string `json:"output_path,omitempty"`
	Ts         int64  `json:"ts"`
}

VerificationRow is one recorded done_criteria run. Reading these back is what lets the UI show *why* a task is green: which commands ran, and that they exited zero. A pass with no visible evidence is indistinguishable from a pass that never ran.

func Verifications added in v0.15.0

func Verifications(ctx context.Context, q Querier, taskID string) ([]VerificationRow, error)

Verifications returns a task's recorded command runs, latest round first.

type Week added in v0.70.0

type Week struct {
	FromMs int64 `json:"from_ms"`
	ToMs   int64 `json:"to_ms"`
	// Days are the seven days in order, each with what it opened and cost.
	Days []WeekDay `json:"days"`
	// Sessions is every hand-run session with a non-internal event in the
	// window; ScheduledSessions those left out because they ran at a root or
	// in the home directory itself (RootOrHome).
	Sessions          int64 `json:"sessions"`
	ScheduledSessions int64 `json:"scheduled_sessions"`
	ActiveDays        int   `json:"active_days"`
	Turns             int64 `json:"turns"`
	// CostUSD is the stored list-price cost of the window's turns: priced once
	// per message id and never twice across forks (TurnPaidElsewhere).
	CostUSD float64 `json:"cost_usd"`
	// UnpricedTurns carry tokens and no price, so CostUSD leaves them out.
	UnpricedTurns int64 `json:"unpriced_turns,omitempty"`
	// Tokens is every token of the window's events: input, output, cache
	// reads and writes.
	Tokens int64 `json:"tokens"`
	// Models is each model's cost and re-read volume, for the context tax.
	Models []WeekModel `json:"models"`

	PRsOpened int `json:"prs_opened"`
	// PRsMerged is distinct pull requests a successful `gh pr merge` named,
	// by URL, by number, or -- for the current-branch form -- by the one URL
	// the command printed. MergesUnresolved ran but named nothing readable and
	// are not in PRsMerged.
	PRsMerged        int   `json:"prs_merged"`
	MergesUnresolved int   `json:"merges_unresolved"`
	Commits          int   `json:"commits"`
	FilesEdited      int   `json:"files_edited"`
	LinesAdded       int64 `json:"lines_added"`   // estimate: a Write counts its whole file
	LinesRemoved     int64 `json:"lines_removed"` // estimate: as above
	// CIWaitMs is tool time spent in commands that wait on CI; ToolMs is all
	// measured tool time. Only Claude Code's hook plane carries a duration, and
	// parallel calls overlap, so neither is wall-clock time.
	CIWaitMs int64 `json:"ci_wait_ms"`
	ToolMs   int64 `json:"tool_ms"`

	Agents  []WeekAgent  `json:"agents"`
	Loop    *WeekLoop    `json:"loop,omitempty"`
	Biggest *WeekSession `json:"biggest,omitempty"`

	// Repos and AgentPRs are for the API to put GitHub's record beside the
	// agents' own; neither is sent, since both name repositories.
	Repos    []WeekRepo    `json:"-"`
	AgentPRs []WeekAgentPR `json:"-"`
	// SkipSQL is the hand-run filter, a clause on session_id, for the
	// API's own reads of the same window (SubagentTokensByModelSkip).
	SkipSQL string `json:"-"`
}

Week is the measured week. Estimates are named as such in their comments and in the API's `estimates` list; everything else is a count or a sum.

func WeekStats added in v0.70.0

func WeekStats(ctx context.Context, q Querier, o WeekOptions) (Week, error)

WeekStats measures one window. See Week for what each figure means.

type WeekAgent added in v0.70.0

type WeekAgent struct {
	Agent    string  `json:"agent"`
	Subagent bool    `json:"subagent"`
	Turns    int64   `json:"turns"`
	CostUSD  float64 `json:"cost_usd"`
	Sessions int64   `json:"sessions"`
	// Threads is how many distinct subagents ran; 0 for main threads.
	Threads int64 `json:"threads,omitempty"`
}

WeekAgent is one agent's main threads, or its subagents.

func AgentSplit added in v0.70.0

func AgentSplit(ctx context.Context, q Querier, from, to int64) ([]WeekAgent, error)

AgentSplit is the turns and cost of each agent's main threads and of its subagents in [from, to). to <= 0 means no upper bound.

It reads in two steps so the big one is covered (idx_events_turn_agent, migration 0031): turns grouped by session and by whether they carry an agent id, without touching a payload; then, for each session with main-thread turns, one payload asks whether the session is a sidechain. That is the one mark MainThreadWhere reads besides agent_id, and OpenCode writes it on every turn of a child session, so one turn answers for the session. Reading it per event cost 3.5 s on the owner's database (2026-10-04).

type WeekAgentPR added in v0.159.0

type WeekAgentPR struct {
	Repo   string
	Number int
	Opened bool
	Merged bool
	// Day is the index into Days the opening fell on, -1 when not opened.
	Day int
}

WeekAgentPR is one pull request the agents opened or merged in the window, as the transcripts say: Repo is "owner/name", or "dir:<root>" for a merge by number in a directory no `gh pr create` printed a URL from.

type WeekDay added in v0.70.0

type WeekDay struct {
	Day       string  `json:"day"`
	PRsOpened int     `json:"prs_opened"`
	CostUSD   float64 `json:"cost_usd"`
	Active    bool    `json:"active"`
}

WeekDay is one local day of the window.

type WeekLoop added in v0.70.0

type WeekLoop struct {
	SessionID string `json:"-"` // for pricing; never shown
	Agent     string `json:"agent"`
	Tool      string `json:"tool"`
	// Kind is what the repeated call did, in words a card can use without
	// quoting the command: poll, command, edit, fetch, subagent, other.
	Kind    string `json:"kind"`
	Calls   int    `json:"calls"`
	FirstMs int64  `json:"first_ms"`
	LastMs  int64  `json:"last_ms"`
	// TaxUSD is what the loop paid to re-read the conversation, priced the way
	// the live alert prices it (contexttax.PriceSeries) -- an estimate, and
	// absent when none of its calls could be priced (Codex calls carry no
	// message id). TaxPricedCalls says how many calls it covers.
	TaxUSD         float64 `json:"tax_usd,omitempty"`
	TaxPricedCalls int     `json:"tax_priced_calls,omitempty"`
}

WeekLoop is the longest episode the loop detector would have alerted on.

type WeekModel added in v0.70.0

type WeekModel struct {
	Model     string  `json:"model"`
	CacheRead int64   `json:"cache_read"`
	CostUSD   float64 `json:"cost_usd"`
}

WeekModel is one model's share of the week, the input to the context tax.

type WeekOptions added in v0.70.0

type WeekOptions struct {
	// From and To bound the window, [From, To). The caller computes them from
	// local midnights, the same days the Cost screen uses.
	From, To time.Time
	// Loc decides which day an event falls on.
	Loc *time.Location
	// LoopK and LoopWindow are the loop detector's own settings (K calls of
	// one signature within the window), so the card's loop is the alert's loop.
	LoopK      int
	LoopWindow time.Duration
	// Home is the user's home directory: notes an agent writes under
	// ~/.claude are memory, not code, and are not counted as files edited.
	Home string
	// TempDirs are scratch locations whose files are not counted either.
	TempDirs []string
	// Windows compares the home directory without case (RootOrHome).
	Windows bool
}

WeekOptions say which seven days, and how the product detects a loop.

type WeekRepo added in v0.159.0

type WeekRepo struct {
	Root    string
	CostUSD float64
}

WeekRepo is one repository root the window's hand-run sessions worked in (sessions.repo_root, else the cwd), and what its turns cost in the window.

type WeekSession added in v0.70.0

type WeekSession struct {
	SessionID  string  `json:"-"`
	Agent      string  `json:"agent"`
	CostUSD    float64 `json:"cost_usd"`
	Turns      int64   `json:"turns"`
	ActiveDays int     `json:"active_days"`
}

WeekSession is the week's most expensive session, without its name.

type WindowSize added in v0.64.0

type WindowSize struct {
	Days         int   `json:"days"`
	Events       int64 `json:"events"`
	PayloadBytes int64 `json:"payload_bytes"`
}

WindowSize is the events on one side of a day boundary.

type WorkKind added in v0.19.0

type WorkKind string

WorkKind is the kind of work one turn did. It is a closed set: every turn lands in exactly one of these, and they sum to the total.

const (
	// WorkNone is a turn that called no tool at all. Named for what is
	// observable (no tool call), never for what it might have been doing.
	WorkNone WorkKind = "none"
	// WorkEdit is a turn that wrote to a file.
	WorkEdit WorkKind = "edit"
	// WorkCommand is a turn that ran a shell command.
	WorkCommand WorkKind = "command"
	// WorkRead is a turn that read or searched the codebase.
	WorkRead WorkKind = "read"
	// WorkWeb is a turn that fetched or searched the web.
	WorkWeb WorkKind = "web"
	// WorkMCP is a turn that called an MCP tool — the user's own integrations.
	WorkMCP WorkKind = "mcp"
	// WorkOther is a turn that called a tool belonging to none of the above:
	// agent and task control, skills, structured output. It is deliberately
	// last and deliberately vague-sounding, because its members genuinely have
	// nothing in common but "not one of the named kinds".
	WorkOther WorkKind = "other"
)

The categories.

WHY THESE, AND WHAT WAS REJECTED. The cut has to survive the question "is that label true?" for every turn it puts in a row, because a flattering label is an invented number in words (rule 6).

  • Edits and commands are separated because they are the two halves of writing software that cost differently and are acted on differently: an edit-heavy bill and a command-heavy bill suggest opposite things about where the time goes.
  • Reading and searching are ONE row, not two. Read, Grep and Glob are the same activity from the model's side — pulling context into the prompt so it can be reasoned about — and the cost driver is identical: the contents enter the prompt and are billed. Splitting them would invite the reader to compare two numbers that mean the same thing.
  • Web research is its own row rather than folded into "other". Fetching and searching the web is a distinct, recognisable activity whose cost a user can act on (it pulls large pages into the prompt), and on the owner's database it is a real 1.8% rather than a rounding error.
  • MCP tools are their own row because they are the user's OWN integrations. Folding a browser-automation or scraping tool into "other" would hide the cost of the thing the user added themselves, which is exactly the cost they are most able to change.
  • "No tool" is called what it is. It is NOT labelled "conversation", "thinking" or "planning": a turn that called no tool may be answering a question, reasoning, planning, or simply writing prose, and picking one of those as the label would assert something the data does not say. The honest statement is the mechanical one — this turn called no tool — and the UI says exactly that.

func WorkKindOfTurn added in v0.19.0

func WorkKindOfTurn(tools []string) WorkKind

WorkKindOfTurn decides the single kind a turn belongs to from the tools it called. An empty set is WorkNone — the turn called nothing.

It is exported so the classification has exactly one definition, testable on its own and shared by the summary and any future caller. The precedence is applied here and nowhere else.

type WorkShare added in v0.19.0

type WorkShare struct {
	// Kind is one of the WorkKind constants — a stable key the UI maps to a
	// label, never a display string.
	Kind      WorkKind `json:"kind"`
	Turns     int64    `json:"turns"`
	Tokens    int64    `json:"tokens"`
	CostUSD   float64  `json:"cost_usd"`
	TokensPct float64  `json:"tokens_pct"`
	CostPct   float64  `json:"cost_pct"`
}

WorkShare is tokens/cost for one KIND of work — what the money was spent on, beside the existing cuts by model and by project.

Turns, not sessions: a session does many kinds of work, so it cannot be counted once per kind without the column summing to more than the total, while a TURN is charged to exactly one kind by construction (see workkind.go), so turns partition and add up.

CostPct and TokensPct are shares of the range total, computed here rather than in the panel because the denominator is the whole range — a percentage whose base the reader has to guess is what rule 6 exists to prevent. Both are sent because they genuinely differ: cost per token varies by model, so a kind of work done by a cheap model is a larger share of the tokens than of the money.

Jump to

Keyboard shortcuts

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