context

package
v0.1.22 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FileChangesFormatter func(payloadJSON string) string

FileChangesFormatter formats a serialized JSON list of file changes into a display string during RestoreSession. Wired by the tool package on startup.

View Source
var FileChangesRestorer func(payloadJSON string) []string

FileChangesRestorer restores a serialized JSON list of file changes into individual live DIFF: entries during RestoreSession, matching the live turn layout.

Functions

func EstimateTokens

func EstimateTokens(text string) int

EstimateTokens calculates BPE token counts for text.

func ExtractEventContent

func ExtractEventContent(payloadJSON string) string

ExtractEventContent extracts clean human-readable content from event JSON payload string.

func IsEngineReminder

func IsEngineReminder(text string) bool

IsEngineReminder is the exported form of isEngineReminder, used by callers outside this package (e.g. the CLI) that need to filter out engine-injected user_msg events when reconstructing user-facing history.

func Reflect added in v0.1.2

func Reflect(st *store.Store) (int, error)

Reflect consolidates raw experience/hotfile notes into higher-level, retrieval-cheap notes (facts/gotchas) using deterministic heuristics — no extra LLM call. This is the "reflect" step of the retain→recall→reflect discipline and is what keeps BroCode an "efficient anomaly": it compounds past sessions' signal without a vector stack, embeddings server, or a summarization round-trip.

It is cheap (two indexed reads + a few UPSERTs) and safe to call at compaction boundaries and session end. Returns the number of distilled notes created/refreshed.

func RestoreSession

func RestoreSession(m *Manager, events []store.Event) []string

RestoreSession replays a session's stored events into memory WITHOUT re-persisting them (so resume / /sessions switch never duplicates history). It restores only the newest events that fit ~80% of the context window and returns human-readable display lines for the UI log.

Assistant turns keep their real structure (reasoning/content/tool_calls): tool-call-only turns render as a compact summary instead of raw JSON, and tool results are re-paired with their calls so providers that require the tool_calls → result pairing don't break. Engine-injected reminders (loop guard, tool budget, verification failures) are restored for the model but displayed as ⚙️ system notes, not as if the user had typed them.

func SetCompactionRatio

func SetCompactionRatio(r float64)

SetCompactionRatio overrides the adaptive compaction trigger (0 < r <= 0.95). The learn package calls this each turn so the threshold converges to the project's actual usage pattern over time.

func ShrinkwrapAST

func ShrinkwrapAST(content string, filename string) string

ShrinkwrapAST performs semantic AST token compression on large code files. It retains package declarations, imports, types, interfaces, function signatures, and docstrings while stripping internal function bodies, reducing token size by 70%.

func TruncateToolOutput

func TruncateToolOutput(content string, maxChars int) string

TruncateToolOutput applies Section 3.1 Prevention Strategy. Long outputs keep BOTH ends — the head (what the run printed first) and the tail (where test failures and stack traces live) — so the repair loop still sees the error without carrying the full dump. The full output is preserved on disk by the engine's artifact pointer (internal/loop/artifacts.go) when available.

Types

type CompactionSummary

type CompactionSummary struct {
	Goal           string   `json:"goal"`
	FilesTouched   []string `json:"files_touched"`
	DecisionsMade  []string `json:"decisions_made"`
	NextAction     string   `json:"next_action"`
	Constraints    string   `json:"constraints"`
	OpenQuestions  []string `json:"open_questions"`
	LastKnownState string   `json:"last_known_state"`
}

CompactionSummary follows the structured 6-heading format used for context compaction. The six headings (Goal, Files Touched, Decisions Made, Next Action, Constraints, Last Known State) give a continuing agent everything it needs without re-reading the dropped transcript — Next Action and Constraints are the two that most reduce "lost the thread" regressions after compaction.

func (CompactionSummary) Format

func (cs CompactionSummary) Format() string

Format returns the 5-heading markdown representation.

type Manager

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

Manager maintains the live message context, token estimation, and event persistence.

func NewManager

func NewManager(sessionID string, st *store.Store, maxTokens int) *Manager

NewManager creates a context manager connected to SQLite store.

func (*Manager) AppendAssistantTurn

func (m *Manager) AppendAssistantTurn(mode, model, reasoning, content string, toolCalls []provider.ToolCall) error

AppendAssistantTurn adds assistant reasoning, answer content, and tool calls. mode and model stamp the turn's origin (engine mode + active model) so a persisted session can restore each answer with its original badge/label.

func (*Manager) AppendFileDiff added in v0.1.16

func (m *Manager) AppendFileDiff(path, diff string) error

AppendFileDiff records a live per-file diff at the exact moment an edit lands, preserving the true chronological flow in the session history so -c resume never dumps diffs at the bottom of the conversation.

func (*Manager) AppendSystemNote

func (m *Manager) AppendSystemNote(content string) error

AppendSystemNote records a UI/informational message (slash-command output such as /help or /diagnose) to the session store so it survives a -c resume. These are not part of the LLM conversation — only the visible chat history — which is why the engine's AppendUserMessage/AppendAssistantTurn do not cover them and they previously vanished when a session was reloaded.

func (*Manager) AppendToolResult

func (m *Manager) AppendToolResult(toolCallID, content string) error

AppendToolResult adds a tool execution result to the context.

func (*Manager) AppendUserMessage

func (m *Manager) AppendUserMessage(content string) error

AppendUserMessage adds a user message to the context and store.

func (*Manager) Compact

func (m *Manager) Compact(summary CompactionSummary) error

Compact performs structured summary compaction.

Goal-pinning: the FIRST user message carries the turn's goal and constraints. Summarizing it away is the documented compaction failure (governance decay — constraint loss jumps from 0% to 30-59% after compaction, arXiv:2606.22528), so it is re-inserted VERBATIM ahead of the summary, never eligible for summarization. The last keepCount messages stay verbatim as the active tail.

func (*Manager) CompactCount added in v0.1.1

func (m *Manager) CompactCount() int

CompactCount returns how many compactions this conversation has performed (session-level metric, also surfaced per-turn via Engine.turnCompactions).

func (*Manager) ImportAssistantTurn

func (m *Manager) ImportAssistantTurn(mode, model, reasoning, content string, toolCalls []provider.ToolCall)

ImportAssistantTurn restores an assistant turn into memory (tokens counted) WITHOUT re-persisting it to the store. See ImportUserMessage. mode and model carry the turn's original engine mode and model so the restored UI log can render the correct badge.

func (*Manager) ImportToolResult

func (m *Manager) ImportToolResult(toolCallID, content string)

ImportToolResult restores a tool result into memory (tokens counted) WITHOUT re-persisting it to the store. Used when replaying a session's events so resuming never duplicates history. Keeps the assistant tool_calls → tool result pairing intact for providers that require it.

func (*Manager) ImportUserMessage

func (m *Manager) ImportUserMessage(content string)

ImportUserMessage restores a user message into memory (tokens counted) WITHOUT re-persisting it to the store. Used when replaying a session's events so resuming never duplicates history.

func (*Manager) IsStaleContext added in v0.1.2

func (m *Manager) IsStaleContext(newPrompt string) (bool, string)

IsStaleContext returns true (and the old hash) if the new prompt is semantically unrelated to the current conversation. "Stale" = the user asked something completely different from the ongoing task. Detects this by comparing keyword overlap: if <30% of significant words in the new prompt appeared in the current conversation, the context is considered stale. The engine uses this to trigger a partial context reset (keep the pinned goal, drop the working trail) instead of charging ahead into a wrong direction.

func (*Manager) LastUserPrompt

func (m *Manager) LastUserPrompt() string

LastUserPrompt returns the content of the most recent user prompt in context.

func (*Manager) Len added in v0.1.2

func (m *Manager) Len() int

Len returns the number of messages currently in context.

func (*Manager) MaxWindow

func (m *Manager) MaxWindow() int

MaxWindow returns context window capacity limit.

func (*Manager) Messages

func (m *Manager) Messages() []provider.Message

Messages returns a copy of current active messages for the LLM call.

func (*Manager) NeedsCompaction

func (m *Manager) NeedsCompaction() bool

NeedsCompaction checks if token usage exceeds compactionRatio of the window. The budget includes the system prompt, so compaction triggers before the real request (system prompt + messages) can overflow the model's context window.

func (*Manager) ResetCompactCount added in v0.1.1

func (m *Manager) ResetCompactCount()

ResetCompactCount zeroes the session compaction counter.

func (*Manager) ResetStaleContext added in v0.1.2

func (m *Manager) ResetStaleContext(newPrompt string)

ResetStaleContext performs a PARTIAL context reset: drops the message history but preserves session ID, model, and token counters. After this, only the new prompt remains, so the next LLM call sees a clean slate without losing session continuity.

func (*Manager) SessionID

func (m *Manager) SessionID() string

SessionID returns active session ID.

func (*Manager) SetMaxWindow

func (m *Manager) SetMaxWindow(max int)

SetMaxWindow updates the context window capacity. Used when the active model switches to one with a different declared context limit (from the provider config's per-model limit block). Non-positive values are ignored.

func (*Manager) SetModel

func (m *Manager) SetModel(model string)

SetModel records the active model name so token estimation can use the exact BPE tokenizer for that model's encoding (falls back to the heuristic char-count estimator when the model is unset or the tokenizer is unavailable).

func (*Manager) SetSystemPromptTokens

func (m *Manager) SetSystemPromptTokens(n int)

SetSystemPromptTokens records the estimated size of the per-turn system prompt so the context budget accounts for it (see systemPromptTokens).

func (*Manager) Store

func (m *Manager) Store() *store.Store

Store returns connected SQLite store.

func (*Manager) TokenBreakdown added in v0.1.1

func (m *Manager) TokenBreakdown() (user, assistant, tool int)

TokenBreakdown returns the cumulative tokens appended this session by kind: user messages, assistant turns (reasoning + content + tool-call schemas), and tool output digests. Cumulative by design — not reduced by compaction — so it answers "where did this session's tokens go?" (the metrics question), not "how full is the window now?" (TotalTokens).

func (*Manager) TotalContextTokens

func (m *Manager) TotalContextTokens() int

TotalContextTokens is the true on-wire token cost of a request: the conversation messages plus the system prompt that accompanies every call.

func (*Manager) TotalTokens

func (m *Manager) TotalTokens() int

TotalTokens returns accumulated context tokens.

Jump to

Keyboard shortcuts

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