brain

package
v0.160.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 22 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 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

View Source
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 makes at most
	// Batch calls to claude. A session with more unread prose than one read
	// sends (MaxInputChars) is read in chunks, oldest first and back to
	// back, each chunk one of the wake's Batch calls; what is left of it
	// waits for the next wake, which picks it up first. A wake that made a
	// full Batch is followed by the next after Continue, not Interval: while
	// a build has sessions waiting it reads one after another, within the
	// daily cap, so the screen shows it working instead of a pause of five
	// minutes between every four.
	Interval = 5 * time.Minute
	Batch    = 4
	Continue = 3 * time.Second
	// 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.

View Source
const (
	PhaseExtracting = "extracting"
	PhaseLinking    = "linking"
)

A read's phases, in order: claude is asked for the memories, then what it returned is stored and linked into the graph. Reading the session's prose from the database comes before both and takes milliseconds; it is not a phase of its own.

View Source
const (
	StageOff        = "off"        // not turned on, or paused
	StageNoClaude   = "no_claude"  // on, but no claude to read with
	StageLimit      = "limit"      // sessions wait, today's tokens are used
	StageExtracting = "extracting" // claude is reading a session
	StageLinking    = "linking"    // a read's memories are being stored
	StageWaiting    = "waiting"    // sessions wait; the next read is due
	StageUpToDate   = "up_to_date" // nothing waits
)

The build's stages, as Status.Stage names them.

View Source
const (
	// CatchUpBackfill is the backfill: sessions from before the extraction
	// was turned on, read because a backfill reached back to them.
	CatchUpBackfill = "backfill"
	// CatchUpSkipped is the text reads before 2026-10-22 skipped
	// (catchup.go).
	CatchUpSkipped = "skipped"
)

The kinds of catch-up, as CatchUp.Kind names them.

View Source
const (
	KnownDecisions = 30
	KnownRecent    = 40
)

How much of the brain a read is shown: the project's newest current decisions, and its newest memories besides them.

View Source
const (
	// MaxInputChars is the most transcript one read sends. A session with
	// more unread is read in chunks of this size, oldest first: each read
	// sends the oldest unread passages that fit and moves the cursor only
	// past those, so the next read goes on where it stopped.
	MaxInputChars = 24000

	// MinPromptRunes is how much of the user's own prompts make a read
	// worth it without the agent's prose: a decision or a standing rule is
	// mostly said in a prompt ("from now on, never push to master" is 40
	// runes; a few of those, or one explained, pass), while "fix it" and
	// "yes" do not. A read is skipped only when it has neither.
	MinPromptRunes = 200
	// 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.

View Source
const (
	// TLDRModel is the model asked: the cheapest Second Brain uses.
	TLDRModel = DefaultModel
	// TLDRShortRunes is the length under which an answer is its own TL;DR:
	// squeezing it would not make it shorter enough to be worth a call.
	TLDRShortRunes = 280
	// TLDRMaxRunes clips what comes back, should the model run long anyway.
	TLDRMaxRunes = 300
	// TLDRMaxInputChars is the most of one answer a squeeze sends. A longer
	// answer is sent as its first TLDRHeadChars and its last
	// MaxInputChars-TLDRHeadChars: an agent states what it did up front and
	// its result and next step at the end, and the middle is the detail a
	// TL;DR drops anyway.
	TLDRMaxInputChars = 12000
	TLDRHeadChars     = 4000
)

Limits on one squeeze.

View Source
const (
	ExcludeMax = 64
)

Limits on the list: a folder is one absolute path on one line.

View Source
const RetagBatch = 40

RetagBatch is how many memories one re-tag call sends.

View Source
const RetagSchema = `` /* 237-byte string literal not displayed */

RetagSchema is the shape of a re-tag answer, for --json-schema.

View Source
const RetagSystem = `` /* 536-byte string literal not displayed */

RetagSystem is the re-tag's instructions.

View Source
const Schema = `` /* 773-byte string literal not displayed */

Schema is the shape of the answer, for --json-schema.

View Source
const System = `` /* 2621-byte string literal not displayed */

System is the extraction's instructions.

View Source
const TLDRGap = "[… the middle of the answer is left out …]"

TLDRGap marks where the middle of a long answer was left out.

View Source
const TLDRSystem = `` /* 408-byte string literal not displayed */

TLDRSystem is the instructions for one squeeze.

Variables

View Source
var ErrExclude = errors.New("exclude is a list of absolute folders")

ErrExclude is the kind of error CleanExclude returns for a bad entry.

View Source
var ErrNoClaude = errors.New("claude was not found on this computer")

ErrNoClaude is returned when no claude binary can be found.

View Source
var ErrTLDREmpty = errors.New("claude answered with nothing")

ErrTLDREmpty is a squeeze that came back with no text.

Functions

func Argv

func Argv(r Request, settingsPath string, batch bool) ([]string, string)

Argv is the command line and the stdin for a request. With batch (a Windows .cmd shim) nothing that holds JSON or quotes goes on the command line: the instructions and the schema go into stdin instead.

func CleanExclude added in v0.157.0

func CleanExclude(in []string) ([]string, error)

CleanExclude puts the list into the form it is kept in: each entry trimmed and in the store's path form, duplicates and empty lines dropped, the order kept. An entry that is not an absolute path, has a line break or a NUL, or is over 1,024 bytes, or a list over ExcludeMax entries, is an error wrapping ErrExclude.

func ExcludedFolder added in v0.157.0

func ExcludedFolder(exclude []string, cwd, repoRoot string) (string, bool)

ExcludedFolder is the excluded folder a session falls under — by its working directory, else its repository root — and whether there is one.

func ExcludedProjects added in v0.157.0

func ExcludedProjects(exclude []string) []string

ExcludedProjects are the project labels of the excluded folders, as the sessions in them are labelled (store.ProjectFromCwd), without repeats or empties: what a graph read, a search, the handoff and the current decisions leave out.

func MeasureGap added in v0.148.0

func MeasureGap(ctx context.Context, q store.Querier, g store.BrainGap) (to int64, reads int, err error)

MeasureGap finds what one past read skipped: the last event of the span it never sent (0 when it skipped nothing) and how many reads that span takes now.

func ParseRetag added in v0.148.0

func ParseRetag(raw json.RawMessage, sent []store.BrainNode) (map[int64][]string, error)

ParseRetag reads a re-tag answer into keywords per memory id, keeping only the ids the batch sent (the first answer for an id wins).

func RetagPrompt added in v0.148.0

func RetagPrompt(mems []store.BrainNode) string

RetagPrompt lists the memories one re-tag call sends, one per line: `#id kind: title — summary`.

func TLDRInput added in v0.128.0

func TLDRInput(text string) string

TLDRInput is the part of an answer a squeeze sends: all of it up to TLDRMaxInputChars characters (runes), else its head and its tail around a marker.

func TLDRShort added in v0.128.0

func TLDRShort(text string) bool

TLDRShort reports whether text is short enough to be its own TL;DR.

Types

type Build added in v0.120.0

type Build struct {
	// From is the start of what is in reach, unix ms (the earlier of `since`
	// and `backfill_since`).
	From int64 `json:"from"`
	// Sessions is Read plus Pending: the sessions in reach that are read, or
	// quiet and waiting to be. A live session joins once it goes quiet.
	Sessions int `json:"sessions"`
	Read     int `json:"read"`
	// Memories is what the reads of those sessions kept.
	Memories int `json:"memories"`
	// Truncated is set when the waiting sessions were counted only to 200.
	Truncated bool `json:"truncated,omitempty"`
	// Sources is the same per project, most sessions first, at most 12.
	Sources []BuildSource `json:"sources"`
}

Build is how far the extraction has got through the sessions in reach.

type BuildSource added in v0.120.0

type BuildSource struct {
	Project  string `json:"project"`
	Read     int    `json:"read"`
	Pending  int    `json:"pending"`
	Memories int    `json:"memories"`
}

BuildSource is one project's share of a build.

type CatchUp added in v0.148.0

type CatchUp struct {
	// Kind is what is being caught up on, one of the CatchUp* values.
	Kind string `json:"kind"`
	Done int    `json:"done"`
	// Total is Done plus the reads left; Truncated when those were counted
	// only to 200.
	Total     int  `json:"total"`
	Truncated bool `json:"truncated,omitempty"`
	// DaysLeft is an estimate: the reads left, times the mean tokens of the
	// reads in the last 14 days, over the daily limit, rounded up. 0 (and
	// absent) before any read has been measured.
	DaysLeft int `json:"days_left,omitempty"`
}

CatchUp is the progress of reading something the extraction has not reached on its own: how many reads are done of how many, and about how many days are left at the daily limit. A screen shows a line while one is present and hides it otherwise.

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.

func (ClaudeRunner) Run

func (c ClaudeRunner) Run(ctx context.Context, r Request) (Result, error)

Run makes one call.

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
	// HandoffOn reports whether new sessions are handed what the last one
	// left (Settings → Memory between sessions), which is how memories reach
	// agents. Nil reads as off.
	HandoffOn 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) DailyTokens added in v0.148.0

func (e *Engine) DailyTokens() int64

DailyTokens is the daily limit the reads keep to.

func (*Engine) Enabled

func (e *Engine) Enabled() bool

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

func (e *Engine) EstimateFrom(ctx context.Context, since int64) (Estimate, error)

EstimateFrom counts what a backfill to `since` would read.

func (*Engine) FindGaps added in v0.148.0

func (e *Engine) FindGaps(ctx context.Context) error

FindGaps measures the gaps migration 0068 listed and not measured yet: each gets its span and its reads, or is deleted when its read skipped nothing. Done once; a later call finds nothing to do.

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) ScrubOnce added in v0.150.0

func (e *Engine) ScrubOnce(ctx context.Context)

ScrubOnce redacts, once per database, the credentials and payment details in the memories and note excerpts kept before the privacy filter (store.ScrubBrainSecrets), in one transaction, and marks it done in meta (store.MetaBrainScrubbed). It runs whether or not the extraction is on: memories made earlier, by hand or imported, are handed on all the same. The log line holds counts by kind, never a value. A failure is logged and tried again on the next start.

func (*Engine) Start

func (e *Engine) Start(ctx context.Context)

Start runs the extraction until ctx ends: a first wake a minute after start, then every Interval, and at once after Kick.

func (*Engine) Status

func (e *Engine) Status(ctx context.Context) Status

Status reports the extraction's state.

func (*Engine) Wait added in v0.123.0

func (e *Engine) Wait()

Wait blocks until the loop Start began has returned, after its context ended; at once when Start never ran. The daemon waits here before closing the database a wake reads.

func (*Engine) Wake

func (e *Engine) Wake(ctx context.Context) (int, error)

Wake reads up to Batch sessions, if the extraction may run, and returns how many calls it made. With no session waiting it re-tags memories that have no keywords instead (retag.go). One wake at a time.

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 Handoff added in v0.122.0

type Handoff struct {
	// On is whether new sessions are handed anything at all.
	On          bool `json:"on"`
	Sessions24h int  `json:"sessions_24h"`
	Memories24h int  `json:"memories_24h"`
	Sessions    int  `json:"sessions"`
	Memories    int  `json:"memories"`
}

Handoff is how often memories reached agents: sessions started that were handed some, and how many memories in all, in the last 24 hours and since it was first counted (migration 0058).

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 was sent, before clipping.
	ProseRunes int
	// PromptRunes is how much of the user's prompts was sent, before
	// clipping.
	PromptRunes int
	// Through is the event id of the last passage given that the prompt
	// covers: how far a read of it may move the session's cursor. Cut is
	// set when passages after it did not fit and wait for the next read.
	Through int64
	Cut     bool
	// Shown are the existing memories the prompt lists, by id; Decisions
	// the current decisions among them, which an answer may supersede.
	Shown     map[int64]bool
	Decisions map[int64]bool
}

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, oldest first, and writes the prompt: the project, the topics already in the brain, then the passages, as many of the oldest as fit in MaxInputChars. What does not fit is left for the next read (Through, Cut); nothing is skipped.

func BuildInputKnown added in v0.148.0

func BuildInputKnown(project string, topics []string, known Known, passages []store.BrainPassage) Input

BuildInputKnown is BuildInput with the project's current decisions and recent memories listed before the passages (Known).

func (Input) WorthReading added in v0.148.0

func (in Input) WorthReading() bool

WorthReading reports whether a read of it is worth a call: enough of the agent's prose, or enough of the user's prompts, where decisions are said.

type Known added in v0.148.0

type Known struct {
	Decisions []store.BrainNode
	Recent    []store.BrainNode
}

Known is what a read is shown of the project's brain: its current decisions and the memories already kept, each with its id, so the answer can supersede a decision, link to a memory and not repeat one.

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"`
	// Keywords are English search words, whatever the title's language.
	Keywords []string `json:"keywords,omitempty"`
	// Supersedes are ids of shown current decisions this one replaces;
	// RelatedIDs and ContradictsIDs ids of shown existing memories.
	Supersedes     []int64 `json:"supersedes,omitempty"`
	RelatedIDs     []int64 `json:"related_ids,omitempty"`
	ContradictsIDs []int64 `json:"contradicts_ids,omitempty"`
}

Memory is one memory as the model returns it.

type Reading added in v0.120.0

type Reading struct {
	SessionID string `json:"session_id"`
	// Title is the session's own name, else its first prompt, clipped.
	Title   string `json:"title,omitempty"`
	Agent   string `json:"agent,omitempty"`
	Project string `json:"project,omitempty"`
	// LastEventAt is when the session last did something; StartedAt when
	// this read began. Unix ms.
	LastEventAt int64 `json:"last_event_at,omitempty"`
	StartedAt   int64 `json:"started_at"`
	// Phase is PhaseExtracting while claude is asked, PhaseLinking while
	// its memories are stored and linked.
	Phase string `json:"phase"`
	// Passages is how many passages of the session's prose were sent.
	Passages int `json:"passages"`
}

Reading is the session a read is asking claude about, for the status's "reading now" line.

type Request

type Request struct {
	System string
	Prompt string
	Model  string
	// Plain asks for a plain-text answer (Result.Text) instead of memories:
	// no --json-schema, nothing parsed out of the text. AI;DR uses it
	// (ADR-072).
	Plain bool
	// Schema, when set, is the answer's shape instead of the memories'
	// (Schema): the answer is then read from Result.JSON. The re-tag uses it.
	Schema string
}

Request is one extraction call.

type Result

type Result struct {
	Memories []Memory
	// Text is the answer's text as claude returned it (`result`).
	Text string
	// JSON is the structured answer as claude returned it (its
	// structured_output, else the first JSON object in the text), for a
	// request with its own Schema.
	JSON      json.RawMessage
	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

func ParseResult(b []byte) (Result, error)

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.

func ParseText added in v0.128.0

func ParseText(b []byte) (Result, error)

ParseText reads claude's JSON result for a plain-text request: the text, the tokens and the cost it reported.

type Retag added in v0.148.0

type Retag struct {
	Done  int `json:"done"`
	Total int `json:"total"`
}

Retag is the re-tag's progress for the status: Done the memories it has given keywords, Total that plus the memories still waiting.

type Runner

type Runner interface {
	Run(ctx context.Context, r Request) (Result, error)
}

Runner makes the call. ClaudeRunner runs the user's claude; tests use a function or the fake claude in testdata.

type RunnerFunc

type RunnerFunc func(ctx context.Context, r Request) (Result, error)

RunnerFunc adapts a function to a Runner.

func (RunnerFunc) Run

func (f RunnerFunc) Run(ctx context.Context, r Request) (Result, error)

Run calls f.

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; SpentUSD what
	// claude reported they cost (at API list price), summed.
	Spent    int64   `json:"spent"`
	SpentUSD float64 `json:"spent_usd"`
	// Stage is where the build is, one of the Stage* values.
	Stage string `json:"stage"`
	// LastRead is when the newest read that kept something finished, unix ms.
	LastRead int64 `json:"last_read,omitempty"`
	// NewToday is the memories added since local midnight, by hand or read.
	NewToday int `json:"new_today"`
	// Topics and Links are the graph's topics and the links between nodes.
	Topics int `json:"topics"`
	Links  int `json:"links"`
	// Handoff is how the memories reach agents: a new session in a
	// repository is handed up to five of its memories with the handoff.
	Handoff Handoff `json:"handoff"`
	Running bool    `json:"running"`
	// Pending is how many sessions wait to be read (counted up to 200).
	Pending int `json:"pending"`
	// Reading is the session being read right now, while a read runs.
	Reading *Reading `json:"reading,omitempty"`
	// Build is the progress through everything in reach — the sessions
	// since `since` or `backfill_since` — while it is on.
	Build *Build `json:"build,omitempty"`
	// CatchUp is a catch-up's progress while one has reads left — the
	// skipped text (kind `skipped`) first, else the backfill (`backfill`) —
	// while it is on; null otherwise. Generic, so each kind reports the
	// same way.
	CatchUp *CatchUp `json:"catch_up"`
	// Retag is the re-tag's progress while memories without keywords wait
	// for it and it is on.
	Retag *Retag `json:"retag,omitempty"`
	// Exclude is the folders whose sessions are never read (Settings →
	// Second Brain), in the store's path form; [] when none.
	Exclude []string `json:"exclude"`
	// Automation24h is how many sessions started with `automation: true` in
	// the last 24 hours, which the extraction skipped unread.
	Automation24h int   `json:"automation_24h"`
	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"`
	// Agents24h is the agents whose sessions a read went through in the
	// last 24 hours, most sessions first: the faces on the sidebar's card.
	Agents24h []store.BrainAgentRead `json:"agents_24h"`
}

Status is the extraction's state for GET /v1/brain/status.

type TLDR added in v0.128.0

type TLDR struct {
	Text    string
	Model   string
	CostUSD float64
}

TLDR is one squeeze's answer.

func Squeeze added in v0.128.0

func Squeeze(ctx context.Context, r Runner, text string) (TLDR, error)

Squeeze asks r for one answer's TL;DR. The caller has already decided the answer is long enough (TLDRShort) and bounds the call with ctx.

Jump to

Keyboard shortcuts

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