Documentation
¶
Index ¶
- Variables
- func EstimateTokens(text string) int
- func ExtractEventContent(payloadJSON string) string
- func IsEngineReminder(text string) bool
- func Reflect(st *store.Store) (int, error)
- func RestoreSession(m *Manager, events []store.Event) []string
- func SetCompactionRatio(r float64)
- func ShrinkwrapAST(content string, filename string) string
- func TruncateToolOutput(content string, maxChars int) string
- type CompactionSummary
- type Manager
- func (m *Manager) AppendAssistantTurn(mode, model, reasoning, content string, toolCalls []provider.ToolCall) error
- func (m *Manager) AppendFileDiff(path, diff string) error
- func (m *Manager) AppendSystemNote(content string) error
- func (m *Manager) AppendToolResult(toolCallID, content string) error
- func (m *Manager) AppendUserMessage(content string) error
- func (m *Manager) Compact(summary CompactionSummary) error
- func (m *Manager) CompactCount() int
- func (m *Manager) ImportAssistantTurn(mode, model, reasoning, content string, toolCalls []provider.ToolCall)
- func (m *Manager) ImportToolResult(toolCallID, content string)
- func (m *Manager) ImportUserMessage(content string)
- func (m *Manager) InjectContextMessage(content string)
- func (m *Manager) IsStaleContext(newPrompt string) (bool, string)
- func (m *Manager) LastUserPrompt() string
- func (m *Manager) Len() int
- func (m *Manager) MaxWindow() int
- func (m *Manager) Messages() []provider.Message
- func (m *Manager) NeedsCompaction() bool
- func (m *Manager) ResetCompactCount()
- func (m *Manager) ResetStaleContext(newPrompt string)
- func (m *Manager) SessionID() string
- func (m *Manager) SetMaxWindow(max int)
- func (m *Manager) SetModel(model string)
- func (m *Manager) SetSystemPromptTokens(n int)
- func (m *Manager) Store() *store.Store
- func (m *Manager) TokenBreakdown() (user, assistant, tool int)
- func (m *Manager) TotalContextTokens() int
- func (m *Manager) TotalTokens() int
Constants ¶
This section is empty.
Variables ¶
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.
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 ¶
EstimateTokens calculates BPE token counts for text.
func ExtractEventContent ¶
ExtractEventContent extracts clean human-readable content from event JSON payload string.
func IsEngineReminder ¶
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
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 ¶
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 ¶
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 ¶
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 TruncateToolOutput limits the length of raw tool outputs before appending to context. It guarantees the returned string NEVER exceeds maxChars.
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 ¶
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
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 ¶
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 ¶
AppendToolResult adds a tool execution result to the context.
func (*Manager) AppendUserMessage ¶
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
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 ¶
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 ¶
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) InjectContextMessage ¶ added in v0.1.47
InjectContextMessage adds a message to the in-memory context (so the model sees it) WITHOUT persisting to the store (so it doesn't show in chat history or appear on -c resume). Used for internal loop-guard messages that should steer the model but never pollute the user's conversation.
func (*Manager) IsStaleContext ¶ added in v0.1.2
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 ¶
LastUserPrompt returns the content of the most recent user prompt in context.
func (*Manager) NeedsCompaction ¶
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
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) SetMaxWindow ¶
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 ¶
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 ¶
SetSystemPromptTokens records the estimated size of the per-turn system prompt so the context budget accounts for it (see systemPromptTokens).
func (*Manager) TokenBreakdown ¶ added in v0.1.1
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 ¶
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 ¶
TotalTokens returns accumulated context tokens.