Help us shape the future of Go! Take the 2026 Go Developer Survey

store

package
v0.1.59 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// KnowledgeMaxEntries is the hard cap on the knowledge table size.
	// Older, low-weight entries are pruned when exceeded.
	KnowledgeMaxEntries = 50

	// KnowledgeMaxNeighbors caps co-read links per entry.
	KnowledgeMaxNeighbors = 3

	// KnowledgeMaxTags caps extracted keywords per entry.
	KnowledgeMaxTags = 8
)

Variables

This section is empty.

Functions

func DetectReplayPrefix added in v0.1.50

func DetectReplayPrefix(events []Event) (int, bool)

func FormatKnowledgeHints added in v0.1.2

func FormatKnowledgeHints(entries []KnowledgeEntryRow, query string) string

FormatKnowledgeHints renders knowledge entries into a compact system-prompt block for injection by the engine. For each relevant file it also lists the matched symbols with their line spans, so the model knows exactly where to jump (read_file(start_line/end_line)) instead of re-reading the whole file. `query` (the current prompt) is used to prioritize the symbols whose names match — so a query like "omega handler" surfaces omega(L4953-4953) first, even inside a 5000-line file whose first symbols are unrelated.

Types

type Event

type Event struct {
	ID          int64      `json:"id"`
	SessionID   string     `json:"session_id"`
	Seq         int        `json:"seq"`
	Type        string     `json:"type"` // 'user_msg' | 'reasoning' | 'tool_call' | 'tool_result' | 'compaction_summary' | 'assistant_msg'
	PayloadJSON string     `json:"payload_json"`
	Tokens      int        `json:"tokens"`
	CreatedAt   time.Time  `json:"created_at"`
	HiddenAt    *time.Time `json:"hidden_at,omitempty"`
}

Event represents an append-only log entry in the events table.

type KnowledgeEntry added in v0.1.2

type KnowledgeEntry struct {
	Hash      string          `json:"hash"`              // sha1 of content (first 8 hex chars)
	Language  string          `json:"lang"`              // detected stack ("go", "ts", "python", ...)
	Tags      []string        `json:"tags"`              // extracted keywords (func names, imports)
	Neighbors []KnowledgeLink `json:"neighbors"`         // files frequently co-read (max 3)
	Symbols   []SymbolRange   `json:"symbols,omitempty"` // whole-file structural index (name→line span)
}

KnowledgeEntry is a single node in the Smart Context Graph. It records what BroCode has previously analyzed about a file so it can avoid re-scanning unchanged content and surface learned relationships.

type KnowledgeEntryRow added in v0.1.2

type KnowledgeEntryRow struct {
	Key    string
	Entry  KnowledgeEntry
	Weight float64
	SeenAt time.Time
}

KnowledgeEntryRow joins the DB row with the parsed payload.

type KnowledgeLink struct {
	Path   string  `json:"p"` // e.g. "src/middleware/auth.go"
	Weight float64 `json:"w"` // 0.0 - 1.0 co-occurrence score
}

KnowledgeLink is a weighted edge to another file.

type Note added in v0.1.2

type Note struct {
	ID         int64     `json:"id"`
	Kind       NoteKind  `json:"kind"`
	Subject    string    `json:"subject"`    // file path / query / topic
	Content    string    `json:"content"`    // outcome or distilled insight
	Tags       []string  `json:"tags"`       // keywords for retrieval
	Provenance string    `json:"provenance"` // "tool=... target=... outcome=..."
	Weight     float64   `json:"weight"`
	Confidence float64   `json:"confidence"` // 0..1, meaningful for beliefs/facts
	CreatedAt  time.Time `json:"created_at"`
	LastSeen   time.Time `json:"last_seen"`
}

Note is a single self-documenting record in the unified context store.

type NoteKind added in v0.1.2

type NoteKind string

NoteKind classifies a durable, searchable note captured from agent activity. The taxonomy follows the retain→recall→reflect discipline: raw experiences are distilled (by the reflection pass) into facts/beliefs/decisions/gotchas that are cheaper to retrieve and higher-signal for future sessions.

const (
	// NoteExperience is a raw, provenance-tagged record of an agent action
	// (what tool, what target, what outcome). High-volume, low-abstraction.
	NoteExperience NoteKind = "experience"
	// NoteHotfile marks a file the agent touches repeatedly this session.
	NoteHotfile NoteKind = "hotfile"
	// NoteFact is a distilled, durable insight (from reflection).
	NoteFact NoteKind = "fact"
	// NoteBelief is an evolving conclusion carrying a confidence score.
	NoteBelief NoteKind = "belief"
	// NoteDecision records an architectural/product decision.
	NoteDecision NoteKind = "decision"
	// NoteGotcha records a trap/pitfall learned the hard way.
	NoteGotcha NoteKind = "gotcha"
)

type PermissionEvent added in v0.1.50

type PermissionEvent struct {
	Command    string `json:"command"`
	Pattern    string `json:"pattern"`     // normalized pattern (e.g. "git commit")
	Decision   string `json:"decision"`    // "allow" | "deny" | "allow_session"
	TrustLevel int    `json:"trust_level"` // trust count at time of decision
}

PermissionEvent records a user's approval/denial of a gated command.

type PhaseTransitionEvent added in v0.1.50

type PhaseTransitionEvent struct {
	From   string `json:"from"` // "RESEARCH" | "EXECUTE" | "VERIFY"
	To     string `json:"to"`
	Reason string `json:"reason"` // "edit_made" | "verify_needed" | "done"
}

PhaseTransitionEvent records a phase change in the execution flow.

type Playbook added in v0.1.32

type Playbook struct {
	ID          string    `json:"id"`
	Pattern     string    `json:"pattern"`
	RootCause   string    `json:"root_cause"`
	Solution    string    `json:"solution"`
	Category    string    `json:"category"`
	Occurrences int       `json:"occurrences"`
	CreatedAt   time.Time `json:"created_at"`
	LastUsed    time.Time `json:"last_used"`
}

Playbook represents an automated self-healing error fix entry.

type Session

type Session struct {
	ID          string    `json:"id"`
	CreatedAt   time.Time `json:"created_at"`
	ProjectPath string    `json:"project_path"`
	Status      string    `json:"status"`
	Mode        string    `json:"mode,omitempty"` // last active engine mode ("BUILDER"/"PLANNER"/"MINER")
}

Session represents a single chat/agent session.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store manages SQLite database persistence for sessions and events.

func NewStore

func NewStore(dbPath string) (*Store, error)

NewStore opens or creates the SQLite database at default path.

func (*Store) AppendEvent

func (s *Store) AppendEvent(sessionID string, eventType, payloadJSON string, tokens int) (*Event, error)

AppendEvent appends a new event into the immutable event log.

func (*Store) AppendPermissionEvent added in v0.1.50

func (s *Store) AppendPermissionEvent(sessionID string, ev PermissionEvent) error

AppendPermissionEvent persists a permission decision for session resume.

func (*Store) AppendPhaseTransition added in v0.1.50

func (s *Store) AppendPhaseTransition(sessionID string, ev PhaseTransitionEvent) error

AppendPhaseTransition persists a phase transition for session resume.

func (*Store) AppendTrustUpdate added in v0.1.50

func (s *Store) AppendTrustUpdate(sessionID string, ev TrustUpdateEvent) error

AppendTrustUpdate persists a trust level change for session resume.

func (*Store) CleanupReplayDuplicates

func (s *Store) CleanupReplayDuplicates(sessionID string) (int, error)

CleanupReplayDuplicates removes events that were duplicated by old resume logic (which re-persisted the whole log on every `-c`). It detects the smallest prefix that the full event list repeats exactly, keeps only that prefix, and deletes the repeated tail. Returns the number of events removed.

func (*Store) Close

func (s *Store) Close() error

Close closes the database connection.

func (*Store) CreateSession

func (s *Store) CreateSession(sessionID, projectPath string) error

CreateSession initializes a new session row.

func (*Store) DeleteAllSessions

func (s *Store) DeleteAllSessions() (int, error)

DeleteAllSessions permanently removes every session and all events from the database. Returns the number of events removed.

func (*Store) DeleteSession

func (s *Store) DeleteSession(sessionID string) (int, error)

DeleteSession permanently removes a session and all of its events from the database (the events table has no ON DELETE CASCADE, so events are deleted first). Returns the number of events removed.

func (*Store) GetSession added in v0.1.3

func (s *Store) GetSession(id string) (*Session, error)

GetSession retrieves a single session by ID. It returns an error wrapping sql.ErrNoRows when the session does not exist.

func (*Store) GetSessionEvents

func (s *Store) GetSessionEvents(sessionID string) ([]Event, error)

GetSessionEvents fetches all visible events for a session.

func (*Store) GetSessionMode

func (s *Store) GetSessionMode(sessionID string) (string, error)

GetSessionMode returns the last persisted engine mode for a session, or "" when the session row is missing (callers treat "" as BUILDER).

func (*Store) InvalidateKnowledge added in v0.1.2

func (s *Store) InvalidateKnowledge(key string) error

InvalidateKnowledge removes a knowledge entry. Called synchronously on edit_file / write_file / delete_file to prevent serving stale hashes. Retries up to 3 times with exponential backoff to handle SQLite write contention from concurrent async knowledge updates.

func (*Store) ListPlaybooks added in v0.1.32

func (s *Store) ListPlaybooks(limit int) ([]Playbook, error)

ListPlaybooks retrieves the top playbooks stored in the database.

func (*Store) ListSessions

func (s *Store) ListSessions() ([]Session, error)

ListSessions retrieves all sessions from the SQLite database.

func (*Store) ListSessionsByProjectPath

func (s *Store) ListSessionsByProjectPath(projectPath string) ([]Session, error)

ListSessionsByProjectPath retrieves sessions created in specific directory path.

func (*Store) MatchPlaybook added in v0.1.32

func (s *Store) MatchPlaybook(errText string) (*Playbook, error)

MatchPlaybook searches for a playbook whose pattern matches the given error text.

func (*Store) NotesByKind added in v0.1.2

func (s *Store) NotesByKind(kind NoteKind, limit int) ([]Note, error)

NotesByKind returns up to `limit` notes of a single kind, highest-weight first. Used by the reflection pass to distill raw experiences into durable, retrieval-cheap notes.

func (*Store) PruneKnowledge added in v0.1.2

func (s *Store) PruneKnowledge() (int, error)

PruneKnowledge removes entries with weight < knowledgePruneWeight and age > knowledgePrunAge. Returns the number of entries pruned.

func (*Store) PruneNotes added in v0.1.2

func (s *Store) PruneNotes() (int, error)

PruneNotes removes low-weight, stale notes (mirrors PruneKnowledge).

func (*Store) QueryKnowledge added in v0.1.2

func (s *Store) QueryKnowledge(prompt string) ([]KnowledgeEntryRow, error)

QueryKnowledge returns up to `limit` knowledge entries whose key or tags relate to the prompt. Uses a simple keyword overlap heuristic (no BM25 dependency). Results are ordered by weight descending.

func (*Store) QueryNotesForPrompt added in v0.1.2

func (s *Store) QueryNotesForPrompt(query string, limit int) ([]Note, error)

QueryNotesForPrompt returns high-signal distilled notes (facts/beliefs/ decisions/gotchas) relevant to a prompt, for warm-start injection. Raw experiences are excluded — they are consolidation fuel, not prompt content.

func (*Store) RecallNotes added in v0.1.2

func (s *Store) RecallNotes(query string, kinds []NoteKind, limit int) ([]Note, error)

RecallNotes searches the notes store by keyword overlap, optionally filtered by kind. Returns up to `limit` notes ordered by combined weight+relevance. This is the agent-facing "context_recall" query: active self-retrieval.

func (*Store) RecordNote added in v0.1.2

func (s *Store) RecordNote(kind NoteKind, subject, content, provenance string, tags []string) error

RecordNote stores (or reinforces) a note. Repeated identical (kind, subject) pairs bump weight and refresh last_seen instead of bloating the table.

func (*Store) RecordPlaybook added in v0.1.32

func (s *Store) RecordPlaybook(pattern, rootCause, solution, category string) error

RecordPlaybook stores or increments a solution playbook for a verified error pattern.

func (*Store) TopNotes added in v0.1.2

func (s *Store) TopNotes(kinds []NoteKind, limit int) ([]Note, error)

TopNotes returns the highest-weight notes across the given kinds, regardless of a query — used to seed architecture/context awareness every session even when the user's prompt is vague. Bounded by `limit` and recency-weighted.

func (*Store) UpdateKnowledge added in v0.1.2

func (s *Store) UpdateKnowledge(key, language string, content string, neighbors []KnowledgeLink, symbols []SymbolRange) error

UpdateKnowledge stores a knowledge entry for a file. Called asynchronously after read_file succeeds. If the entry already exists with the same hash, only `weight` is incremented (reinforcement learning signal). `symbols` is the whole-file structural index (optional; extracted from content when nil).

func (*Store) UpdateSessionMode

func (s *Store) UpdateSessionMode(sessionID, mode string) error

UpdateSessionMode persists the active engine mode for a session so a later resume (`-c` or /sessions) continues in the same mode.

type SymbolRange added in v0.1.2

type SymbolRange struct {
	Name  string `json:"n"` // symbol name (func/method/class/struct…)
	Kind  string `json:"k"` // func | method | class | struct | interface | def | enum | trait
	Start int    `json:"s"` // 1-based start line
	End   int    `json:"e"` // 1-based end line (inclusive)
}

SymbolRange is a structural anchor: a named code unit and the line span it occupies in the source file. It gives the Smart Context Graph POSITION awareness across an entire file — even when only part of the file was ever read into the model's context. This is what lets BroCode answer "where is X in that 5000-line file?" without force-cutting or re-reading everything: the graph knows every symbol's line range, so recall can point straight at it (coarse-to-fine: file → symbol → line span). No embeddings, no vector stack.

type TrustUpdateEvent added in v0.1.50

type TrustUpdateEvent struct {
	Pattern      string `json:"pattern"`
	OldLevel     int    `json:"old_level"`
	NewLevel     int    `json:"new_level"`
	AutoApproved bool   `json:"auto_approved"` // true if threshold reached
}

TrustUpdateEvent records a trust level change for graduated trust.

Jump to

Keyboard shortcuts

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