Documentation
¶
Index ¶
- Constants
- func AutoResolveDependencies(ctx context.Context, repoRoot string, diagText string) (string, bool)
- func CalculateAdaptiveToolBudget(prompt string, mode string) int
- func CheckBlastRadiusImpact(ctx context.Context, repoRoot string, modifiedFile string, ...) []string
- func SelfHealLadder(ctx context.Context, filePath string) (string, bool)
- func TestCommandPlan() []string
- type AgentTurn
- type Engine
- func (e *Engine) AddFallback(fb Fallback)
- func (e *Engine) CostSummary() string
- func (e *Engine) CostUSD() float64
- func (e *Engine) FallbackCount() int
- func (e *Engine) LastFallbackModel() string
- func (e *Engine) LastFallbackReason() string
- func (e *Engine) LearnerStats() string
- func (e *Engine) Mode() string
- func (e *Engine) PrimaryCooldownRemaining() time.Duration
- func (e *Engine) RunTurn(ctx context.Context, userQuery string, onUpdate TurnOutputHandler) (answer string, err error)
- func (e *Engine) RunTurnWithUsage(ctx context.Context, userQuery string, onUpdate TurnOutputHandler) (answer string, tokens int, cost float64, compactions int, err error)
- func (e *Engine) SessionCostUSD() float64
- func (e *Engine) SetAgentPrompt(p string)
- func (e *Engine) SetAskHandler(fn func(question string, options []string) (string, error))
- func (e *Engine) SetBudgetUSD(usd float64)
- func (e *Engine) SetCompactModel(m string)
- func (e *Engine) SetDetectedStacks(stacks []prompt.Stack)
- func (e *Engine) SetDiagnosticsChecker(fn func(path string) string)
- func (e *Engine) SetEarlyExitOnError(v bool)
- func (e *Engine) SetFallbackPolicy(policy string)
- func (e *Engine) SetGlobalIndex(index *search.GlobalIndex)
- func (e *Engine) SetHooks(h *hooks.Manager)
- func (e *Engine) SetKnowledgeStore(st *store.Store)
- func (e *Engine) SetLSPStatus(n int)
- func (e *Engine) SetLearner(l *learn.Learner)
- func (e *Engine) SetMaxIterations(n int)
- func (e *Engine) SetMemoryStore(st *memory.Store)
- func (e *Engine) SetMode(m string)
- func (e *Engine) SetOnChange(fn func(path, diff string))
- func (e *Engine) SetOnFileEdited(fn func(path string))
- func (e *Engine) SetPrimaryIdentity(id, protocol string)
- func (e *Engine) SetProjectContext(pc string)
- func (e *Engine) SetRepoMap(rm string)
- func (e *Engine) SetReviewLLM(on bool)
- func (e *Engine) SetScopeFiles(files []string)
- func (e *Engine) SetScoutManager(sm ScoutDrainer)
- func (e *Engine) SetSkillCatalog(entries []prompt.SkillEntry)
- func (e *Engine) SetStreamHandler(fn func(delta string))
- func (e *Engine) SetSymbolsProvider(fn func() map[string]map[string]bool)
- func (e *Engine) SetToolDescBudget(n int)
- func (e *Engine) SetTuning(t *prompt.Tuning)
- func (e *Engine) SetUsageRecorder(fn func(paths []string))
- func (e *Engine) SetUsageTracker(u *UsageTracker)
- func (e *Engine) State() LoopState
- func (e *Engine) TurnCompactions() int
- func (e *Engine) TurnTokenStats() tokens.TurnTokenStats
- func (e *Engine) TurnTokens() int
- func (e *Engine) UsageTracker() *UsageTracker
- type Fallback
- type LoopState
- type ModelUsage
- type ReviewCouncil
- type ScoutDrainer
- type TreeDebugger
- type TurnOutputHandler
- type TurnSnapshot
- type UsageTracker
Constants ¶
const ( // FallbackAuto (default): retry the primary once on transient errors, then // route to the next healthy fallback, skipping providers in cooldown. FallbackAuto = "auto" // FallbackConfirm asks the user before serving a fallback from a DIFFERENT // vendor than the primary; same-vendor fallbacks route automatically. FallbackConfirm = "confirm" // FallbackPrimaryOnly never falls back — a primary failure ends the turn // with an error. FallbackPrimaryOnly = "primary_only" )
FallbackPolicy controls automatic model routing when the primary provider fails mid-turn.
Variables ¶
This section is empty.
Functions ¶
func AutoResolveDependencies ¶ added in v0.1.41
AutoResolveDependencies inspects compiler / LSP diagnostic errors and automatically runs the project's native package manager to fetch missing modules/dependencies. It is language- and package-manager agnostic (Go, Node/pnpm/yarn/bun, Python/uv/poetry/pip, Rust/cargo, PHP/composer).
func CheckBlastRadiusImpact ¶ added in v0.1.41
func CheckBlastRadiusImpact(ctx context.Context, repoRoot string, modifiedFile string, diagFn func(string) string, index *search.GlobalIndex) []string
CheckBlastRadiusImpact inspects whether modifying an exported symbol in modifiedFile broke any downstream caller files across the repository.
func SelfHealLadder ¶
SelfHealLadder executes deterministic local formatters/fixers on edited files. It repairs syntax formatting (e.g. gofmt, prettier, eslint --fix) locally before wasting LLM turns on minor syntax or formatting errors.
func TestCommandPlan ¶
func TestCommandPlan() []string
TestCommandPlan returns the planned verification commands as shell command lines (for the model-callable run_tests tool), in order, or nil when the project has no recognized test/build system. Reuses planVerification so the harness gate and the on-demand tool never diverge.
Types ¶
type AgentTurn ¶
type AgentTurn struct {
Reasoning string `json:"reasoning"`
ToolCalls []provider.ToolCall `json:"tool_calls,omitempty"`
Answer string `json:"answer,omitempty"`
}
AgentTurn enforces thinking before answering (§2.2).
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine orchestrates the ReAct loop and verification ladder.
func NewEngine ¶
func NewEngine(adapter provider.ProviderAdapter, tools *tool.Registry, ctxMgr *bcontext.Manager, model string) *Engine
NewEngine creates an agent loop engine instance.
func (*Engine) AddFallback ¶
AddFallback registers a fallback provider+model tried on primary failure.
func (*Engine) CostSummary ¶
CostSummary returns the session's estimated cost report (per model + total).
func (*Engine) CostUSD ¶
CostUSD returns the accumulated estimated spend (USD) for the current turn.
func (*Engine) FallbackCount ¶
FallbackCount returns how many turns a fallback provider has served.
func (*Engine) LastFallbackModel ¶
LastFallbackModel returns the fallback model used in the most recent turn (empty when the primary model served the turn).
func (*Engine) LastFallbackReason ¶
LastFallbackReason returns the primary provider's error that triggered the fallback routing on the most recent turn (empty when the primary served it cleanly). Used by the CLI banner to report why a fallback model answered.
func (*Engine) LearnerStats ¶
LearnerStats returns the self-improving layer's status line for the HUD/debug.
func (*Engine) PrimaryCooldownRemaining ¶
PrimaryCooldownRemaining returns how much longer the primary provider will be skipped before the router tries it again (0 if healthy or uncooldown).
func (*Engine) RunTurnWithUsage ¶ added in v0.1.1
func (e *Engine) RunTurnWithUsage(ctx context.Context, userQuery string, onUpdate TurnOutputHandler) (answer string, tokens int, cost float64, compactions int, err error)
RunTurnWithUsage runs a full turn and additionally returns the raw token count and estimated cost attributed to it. Both are available on the error path too, so callers (sub-agents, phase attribution) can bill partial work when a turn fails partway through.
func (*Engine) SessionCostUSD ¶
SessionCostUSD returns the total estimated spend so far (for the footer).
func (*Engine) SetAgentPrompt ¶ added in v0.1.36
SetAgentPrompt sets the custom instructions for the active custom agent.
func (*Engine) SetAskHandler ¶
SetAskHandler wires an interactive question handler for turn extensions.
func (*Engine) SetBudgetUSD ¶
SetBudgetUSD caps the turn's total estimated spend in USD. 0 (the default) disables the cap. Applied per user turn — the counter resets when the turn starts.
func (*Engine) SetCompactModel ¶
SetCompactModel routes compaction summarization to a (cheaper) model. Empty uses the active synthesis model.
func (*Engine) SetDetectedStacks ¶ added in v0.1.1
SetDetectedStacks wires the repo's detected languages (with evidence files) so the prompt builder can render a STACK hint and bias the skill-catalog ranking toward the repo.
func (*Engine) SetDiagnosticsChecker ¶
SetDiagnosticsChecker wires a native type-error checker (the UI provides one backed by the LSP manager). It runs on edited files after the convention review, catching type errors without waiting for a full build.
func (*Engine) SetEarlyExitOnError ¶ added in v0.1.2
SetEarlyExitOnError enables stopping remaining tool execution in a round when a mutating tool fails. This prevents the model from cascading into error-after-error when a prerequisite edit/build command fails. Enabled by default.
func (*Engine) SetFallbackPolicy ¶
SetFallbackPolicy sets the routing policy (FallbackAuto / FallbackConfirm / FallbackPrimaryOnly). The default is FallbackAuto.
func (*Engine) SetGlobalIndex ¶ added in v0.1.41
func (e *Engine) SetGlobalIndex(index *search.GlobalIndex)
SetGlobalIndex registers the session-wide symbol and reference index for blast radius analysis.
func (*Engine) SetKnowledgeStore ¶ added in v0.1.2
SetKnowledgeStore wires the Smart Context Graph backend. When set, the engine queries it at turn-start for relevance-ranked file hints and injects them as a "SMART CONTEXT" block in the system prompt — helping the agent avoid re-scanning files it has already analyzed in prior sessions.
func (*Engine) SetLSPStatus ¶
SetLSPStatus records how many language servers are available this session. The system prompt reads it to decide whether lsp_scan is usable and to steer the model away from installing external linters when LSP is missing.
func (*Engine) SetLearner ¶
SetLearner attaches the self-improving control layer. It immediately applies the learned compaction ratio so the session starts with the tuned threshold rather than the default, and observes each turn to keep converging.
func (*Engine) SetMaxIterations ¶
SetMaxIterations overrides the loop iteration cap (default 25). Used by the benchmark harness to bound each case. Setting it also marks the cap as explicit (baseMaxIterations > 0), so the per-turn reset honors it instead of re-deriving a complexity tier.
func (*Engine) SetMemoryStore ¶
SetMemoryStore wires the cross-session project memory. When set, a warm-start excerpt of past sessions' learnings is injected into the system prompt, and compaction summaries are auto-merged back into memory.
func (*Engine) SetOnChange ¶
SetOnChange wires a callback invoked whenever a write/edit tool succeeds, with the file path and its unified diff — so the host can render a live red/green diff entry in the chat as each edit lands.
func (*Engine) SetOnFileEdited ¶
SetOnFileEdited wires a callback invoked whenever a write/edit tool succeeds, so the host can keep session-scoped caches (e.g. the symbol index) fresh.
func (*Engine) SetPrimaryIdentity ¶
SetPrimaryIdentity gives the primary provider a stable ID and wire protocol so the adaptive router can track its health across turns and enforce cross-vendor confirmation policies.
func (*Engine) SetProjectContext ¶
SetProjectContext injects a compact structural overview of the project into every turn's system prompt (see search.BuildProjectContext). Empty disables.
func (*Engine) SetRepoMap ¶
SetRepoMap injects the deterministic project map (entry points, structure, hot files by usage) into every turn's system prompt. Empty disables.
func (*Engine) SetReviewLLM ¶
SetReviewLLM toggles the senior-level LLM code review (Layer 2) that runs after the deterministic checks pass. On by default; turn off where an extra completion per edit is not worth it (tests, cheap/headless contexts).
func (*Engine) SetScopeFiles ¶ added in v0.1.2
SetScopeFiles injects the full project file list for smart scope pre-selection: given a user prompt, ScoreFiles() ranks files by relevance so BroCode can focus exploration on the most likely targets instead of scanning the entire workspace. Empty disables.
func (*Engine) SetScoutManager ¶
func (e *Engine) SetScoutManager(sm ScoutDrainer)
SetScoutManager wires the background scout manager. Nil disables scout result delivery (the scout tool itself then reports an error).
func (*Engine) SetSkillCatalog ¶ added in v0.1.1
func (e *Engine) SetSkillCatalog(entries []prompt.SkillEntry)
SetSkillCatalog injects the installed skill catalog (name + description only; the model loads each SKILL.md itself). Empty disables the skills block. The catalog is relevance-filtered by the prompt builder when it exceeds the tuning threshold.
func (*Engine) SetStreamHandler ¶
SetStreamHandler wires a callback receiving content deltas while the model streams its answer. Nil disables streaming (adapters fall back to Complete).
func (*Engine) SetSymbolsProvider ¶
SetSymbolsProvider wires a global symbol provider for cross-file duplicate detection and DRY enforcement.
func (*Engine) SetToolDescBudget ¶
SetToolDescBudget caps how many characters of tool descriptions are passed in system prompts. 0 means unlimited.
func (*Engine) SetTuning ¶ added in v0.1.1
SetTuning replaces the runtime tuning surface (block/rule toggles, skill catalog budgets). Nil keeps the defaults.
func (*Engine) SetUsageRecorder ¶
SetUsageRecorder wires a callback that receives the files the model touched each turn (read, searched, edited) so usage can persist across sessions.
func (*Engine) SetUsageTracker ¶ added in v0.1.36
func (e *Engine) SetUsageTracker(u *UsageTracker)
SetUsageTracker shares an existing usage tracker with this engine.
func (*Engine) TurnCompactions ¶ added in v0.1.1
TurnCompactions returns how many context compactions fired during the most recent turn (delta of the session counter, so repeated turns accumulate).
func (*Engine) TurnTokenStats ¶ added in v0.1.2
func (e *Engine) TurnTokenStats() tokens.TurnTokenStats
TurnTokenStats returns the turn's token economy: total tokens vs. the productive subset (answer + file-mutating rounds). The ratio is BroCode's north-star efficiency metric — a high ratio means the agent went straight to the result instead of thrashing through the codebase.
func (*Engine) TurnTokens ¶
TurnTokens returns the raw token count consumed by this turn's completions (per-turn HUD, P2 #3).
func (*Engine) UsageTracker ¶ added in v0.1.36
func (e *Engine) UsageTracker() *UsageTracker
UsageTracker returns the engine's session usage tracker.
type Fallback ¶
type Fallback struct {
// ID is a stable provider identity (e.g. "groq", "opencode") used for
// health tracking in the adaptive router.
ID string
// Protocol is the wire protocol ("anthropic" / "openai-compatible"), used
// by the "confirm" fallback policy to ask only when the fallback is a
// different vendor than the primary.
Protocol string
Adapter provider.ProviderAdapter
Model string
}
Fallback is an alternative adapter+model pair tried when the primary provider fails (automatic model routing).
type ModelUsage ¶
ModelUsage accumulates tokens and estimated cost for one model.
type ReviewCouncil ¶
type ReviewCouncil struct{}
ReviewCouncil performs static peer review audits on critical code changes. It checks for N+1 queries, unhandled errors, and breaking changes.
func NewReviewCouncil ¶
func NewReviewCouncil() *ReviewCouncil
NewReviewCouncil creates a new council reviewer instance.
func (*ReviewCouncil) AuditDiff ¶
func (rc *ReviewCouncil) AuditDiff(filePath, content string) []string
AuditDiff inspects file content changes for architectural or security risks.
func (*ReviewCouncil) FormatFindings ¶
func (rc *ReviewCouncil) FormatFindings(findings []string) string
FormatFindings renders review council alerts into human-readable text.
type ScoutDrainer ¶
type ScoutDrainer interface {
// Drain returns one formatted report per finished job and removes them.
Drain() []string
// Pending returns the number of jobs still running.
Pending() int
}
ScoutDrainer delivers completed background research findings. Implemented by *subagent.ScoutManager; defined here as an interface to avoid an import cycle (subagent imports loop for its isolated sub-loops).
type TreeDebugger ¶
type TreeDebugger struct {
// contains filtered or unexported fields
}
TreeDebugger maintains the interactive time-travel snapshot tree.
func NewTreeDebugger ¶
func NewTreeDebugger() *TreeDebugger
NewTreeDebugger initializes a new Time-Travel Debugger store.
func (*TreeDebugger) RecordTurn ¶
func (td *TreeDebugger) RecordTurn(prompt string, state LoopState, editedFiles []string)
RecordTurn records a turn state checkpoint.
func (*TreeDebugger) TreeView ¶
func (td *TreeDebugger) TreeView() string
TreeView renders the visual conversation state tree (for /tree command).
func (*TreeDebugger) UndoLast ¶
func (td *TreeDebugger) UndoLast() (TurnSnapshot, bool)
UndoLast turns back to the previous snapshot.
type TurnOutputHandler ¶
RunTurn executes the ReAct loop until a terminal state is reached.
type TurnSnapshot ¶
TurnSnapshot records state at a specific turn checkpoint.
type UsageTracker ¶
type UsageTracker struct {
// contains filtered or unexported fields
}
UsageTracker accumulates per-model usage across a session.
func NewUsageTracker ¶
func NewUsageTracker() *UsageTracker
NewUsageTracker creates an empty tracker.
func (*UsageTracker) Record ¶
func (u *UsageTracker) Record(model string, usg provider.Usage)
Record adds one completion's usage under a model name.
func (*UsageTracker) Summary ¶
func (u *UsageTracker) Summary() string
Summary renders a compact multi-line cost report (for /cost).
func (*UsageTracker) TelemetryAdvisor ¶
func (u *UsageTracker) TelemetryAdvisor() string
TelemetryAdvisor analyzes session usage patterns and returns optimization suggestions (Fase 5.2).
func (*UsageTracker) TotalCost ¶
func (u *UsageTracker) TotalCost() float64
TotalCost returns the summed estimated cost across all models.
func (*UsageTracker) TotalTokens ¶
func (u *UsageTracker) TotalTokens() int
TotalTokens returns the summed token usage.