Documentation
¶
Overview ¶
Package brain is Second Brain's automatic extraction (ADR-063): it reads the prose of finished sessions and keeps the few memories worth keeping, linked to their projects and topics, by asking the user's own installed `claude` — headless, through the user's own login, the same place the session itself went. Nothing goes to a server of Caprock's.
Index ¶
Constants ¶
const ( // DefaultModel is passed to claude --model unless the user picks another. DefaultModel = "haiku" // DefaultDailyTokens caps what the extraction spends in a rolling day. DefaultDailyTokens = 300_000 // Interval is how often the extraction wakes; each wake reads at most // Batch sessions. Interval = 5 * time.Minute Batch = 4 // IdleAfter is how long a session must have been quiet before it is read, // so a read sees a finished stretch of work, not the middle of a turn. IdleAfter = 10 * time.Minute // MaxFailures failed reads of one session in a row, and it is skipped. MaxFailures = 4 // OverheadTokens is what one read costs before any transcript: the // instructions and claude's own framing. Measured with Claude Code // 2.1.299 and Haiku on 2026-10-14: 4,318 input tokens for a one-line // transcript. Used only for the backfill's estimate. OverheadTokens = 4300 )
Defaults and pacing. None of these is a claim about cost: what a read costs is what claude reports, recorded per read and summed for the cap.
const ( // MaxInputChars is the most transcript one read sends; when a session // has more, the newest is kept, where its conclusions are. MaxInputChars = 24000 // MinProseRunes is how much of the agent's own prose a session needs // before it is worth a read; less is a quick question, and is skipped. MinProseRunes = 300 )
Limits on what one read sends.
const Schema = `` /* 518-byte string literal not displayed */
Schema is the shape of the answer, for --json-schema.
const System = `` /* 1148-byte string literal not displayed */
System is the extraction's instructions.
Variables ¶
var ErrNoClaude = errors.New("claude was not found on this computer")
ErrNoClaude is returned when no claude binary can be found.
Functions ¶
Types ¶
type ClaudeRunner ¶
type ClaudeRunner struct {
// Binary finds claude; "" when it is not installed.
Binary func() string
// Env is the environment it runs in (the user's login shell's).
Env func() []string
// Dir is an empty working folder of Caprock's.
Dir string
// Timeout bounds one call.
Timeout time.Duration
}
ClaudeRunner runs `claude -p` headlessly. The flags, each checked against `claude --help` of Claude Code 2.1.299 on 2026-10-14:
- `-p --output-format json`: one JSON result on stdout, with `usage`, `total_cost_usd`, `result` and, with --json-schema, `structured_output`.
- `--tools ""`: no tool at all, so the model can only answer.
- `--no-session-persistence`: no transcript is written, so Caprock's own ingest never sees the call as a session.
- `--setting-sources local` with the working directory an empty folder of Caprock's, and `--settings` naming a file that holds `{"disableAllHooks": true}`: the user's hooks — Caprock's shim among them — do not fire, and the user's settings, plugins and memory files are not loaded (measured: about 4,300 input tokens a call instead of 16,600 with them, 2026-10-14). The login is the user's own: it is read from the keychain or credentials file, not from settings.
- `--system-prompt` and `--json-schema`: the instructions and the shape of the answer. A Windows .cmd shim cannot carry JSON on its command line, so there both go into the prompt on stdin and the answer is parsed from the text.
- `--model`: the user's choice, Haiku by default.
The prompt goes on stdin, never on the command line, so a long session is not cut by a command-line limit.
type Engine ¶
type Engine struct {
Store *store.Store
Bus *bus.Bus
Log *slog.Logger
Now func() time.Time
// Config is the extraction's settings, read on every wake.
Config func() config.BrainConfig
// ClaudeFound reports whether a claude binary is installed.
ClaudeFound func() bool
Runner Runner
// contains filtered or unexported fields
}
Engine runs the extraction in the background. Every field but the unexported ones is set before Start.
func (*Engine) Enabled ¶
Enabled reports whether the extraction may run now: a yes from the user. No licence is needed (owner decision, 2026-10-14).
func (*Engine) EstimateFrom ¶
EstimateFrom counts what a backfill to `since` would read.
func (*Engine) Kick ¶
func (e *Engine) Kick()
Kick asks for a wake now (a setting turned on, a backfill asked for). It never blocks and never runs the wake itself: the wake runs on Start's goroutine, under the daemon's context rather than a request's. Kicks that arrive together make one wake, and a wake already running is not doubled (Wake runs one at a time).
func (*Engine) Start ¶
Start runs the extraction until ctx ends: a first wake a minute after start, then every Interval, and at once after Kick.
type Estimate ¶
type Estimate struct {
Sessions int `json:"sessions"`
Tokens int64 `json:"tokens_estimate"`
Days int `json:"days_estimate"`
DailyCap int64 `json:"daily_tokens"`
Truncated bool `json:"truncated,omitempty"`
}
Estimate is what reading back to a moment would take: sessions with enough prose to be read, and the tokens that is likely to cost — an estimate from the transcript's length (about four characters a token) and the measured overhead of one read, not a measurement.
type Input ¶
type Input struct {
Prompt string
Passages []store.BrainPassage // in the order numbered, 1-based
// ProseRunes is how much of the agent's prose there is, before clipping.
ProseRunes int
}
Input is one session's transcript as the extraction sends it.
func BuildInput ¶
func BuildInput(project string, topics []string, passages []store.BrainPassage) Input
BuildInput numbers a session's passages and writes the prompt: the project, the topics already in the brain, then the passages, newest kept when they do not all fit.
type Memory ¶
type Memory struct {
Kind string `json:"kind"`
Title string `json:"title"`
Summary string `json:"summary"`
Topics []string `json:"topics"`
// Passage is the number of the passage it came from, 1-based; 0 when the
// model did not say.
Passage int `json:"passage,omitempty"`
// Related and Contradicts are 0-based indexes of other memories in the
// same answer.
Related []int `json:"related,omitempty"`
Contradicts []int `json:"contradicts,omitempty"`
}
Memory is one memory as the model returns it.
type Result ¶
type Result struct {
Memories []Memory
Model string
TokensIn int64 // input, cache read and cache write
TokensOut int64
CostUSD float64
}
Result is what one call returned and what it cost, as claude reported it.
func ParseResult ¶
ParseResult reads claude's JSON result: the memories (from the structured output, else from the first JSON object in the text), the tokens and the cost it reported.
type Runner ¶
Runner makes the call. ClaudeRunner runs the user's claude; tests use a function or the fake claude in testdata.
type RunnerFunc ¶
RunnerFunc adapts a function to a Runner.
type Status ¶
type Status struct {
// Chosen is whether the user has answered the offer to turn it on;
// Enabled whether it is on (a yes).
Chosen bool `json:"chosen"`
On bool `json:"on"`
Enabled bool `json:"enabled"`
ClaudeFound bool `json:"claude_found"`
Model string `json:"model"`
DailyTokens int64 `json:"daily_tokens"`
// Spent is what the reads used in the last 24 hours.
Spent int64 `json:"spent"`
Running bool `json:"running"`
// Pending is how many sessions wait to be read (counted up to 200).
Pending int `json:"pending"`
Since int64 `json:"since,omitempty"`
BackfillSince int64 `json:"backfill_since,omitempty"`
LastWake int64 `json:"last_wake,omitempty"`
// NextWake is when the next wake is due, unix ms; absent while it is off.
// At or before now when one was just asked for or is running.
NextWake int64 `json:"next_wake,omitempty"`
LastError string `json:"last_error,omitempty"`
// Recent is the newest reads that did something.
Recent []store.BrainRun `json:"recent"`
}
Status is the extraction's state for GET /v1/brain/status.