Skip to content

Split wiring.go builders and eliminate ContextManager state sync dance - #174

Merged
buchenberg merged 4 commits into
mainfrom
feat/split-wiring-context-manager
Aug 7, 2026
Merged

Split wiring.go builders and eliminate ContextManager state sync dance#174
buchenberg merged 4 commits into
mainfrom
feat/split-wiring-context-manager

Conversation

@buchenberg

@buchenberg buchenberg commented Aug 7, 2026

Copy link
Copy Markdown
Owner

Task #11: Split newAgentSessionWithOptions into focused builders

  • wiring_otel.go: initOtel + wrapProviderWithOtel (extracted inline provider wrapping)
  • wiring_mcp.go: initMCP (moved to its own file)
  • wiring_prompt.go: buildSystemPrompt + buildMainPrompt (extracted inline prompt layers, memory enrichment, guidelines, directive injection, and quick-ref assembly)
  • wiring.go slimmed from 396 to ~210 lines; removed dead layers.Skills assignment (was set after prompts.Build, never read)

Task #12: Complete ContextManager extraction — eliminate state sync dance

  • Added State *LoopState pointer to ContextManager; compaction methods now read/write mutable state (Messages, PreviousSummary, token counts, compaction tracking) directly through the pointer instead of copy-in/copy-out
  • Removed 9 duplicate state fields from ContextManager (Messages, PreviousSummary, LastPromptTokens, LastCachedPromptTokens, IneffectiveCompactions, LastCompactionTokens, CompactionBudgetMultiplier, CompactionSavingsHistory, CompactionForcedByOverflow)
  • Eliminated 19-line sync dance in Loop.compactContext and 3-line dance in Loop.trimContext
  • Removed redundant CtxMgr.Messages assignments in loop.go, tools.go, turn.go (now no-ops since CtxMgr.State points to Loop.State)
  • ctxMgr() lazily sets State = &l.State when nil (backward compatible with tests)

Summary by CodeRabbit

  • New Features

    • Added optional integration with configured tool servers, with startup errors reported without preventing the application from launching.
    • Added configurable tracing and observability support, including endpoint and environment-based configuration.
    • Improved prompt assembly with clearer session guidance, tool references, project context, and optional stored-memory guidance.
  • Bug Fixes

    • Improved conversation context management to keep messages and compaction state synchronized, supporting more reliable trimming and summarization during long sessions.

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@buchenberg, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 19 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 0dadfb21-8cf5-4da9-a9af-2e9127bbd6ba

📥 Commits

Reviewing files that changed from the base of the PR and between a8d29d5 and 6bc0d2c.

📒 Files selected for processing (25)
  • .agents/plans/max-iterations-continue-dialog/PLAN.md
  • .agents/plans/tui-mcp-bridge/PLAN.md
  • .agents/plans/tui-quiet-mode/PLAN.md
  • .agents/plans/tui2-task-pane-separation/PLAN.md
  • .agents/plans/web-ui-commands/PLAN.md
  • .kilo/plans/1784602976760-architecture-review.md
  • CONTRIBUTING.md
  • cmd/yaah/wiring.go
  • cmd/yaah/wiring_mcp.go
  • cmd/yaah/wiring_otel.go
  • cmd/yaah/wiring_prompt.go
  • docs/PROMPT-INJECTION.md
  • docs/adr/0001-engine-view-separation.md
  • docs/adr/0002-middleware-pipeline.md
  • docs/adr/0003-functional-options.md
  • docs/adr/0004-event-driven-architecture.md
  • docs/adr/README.md
  • docs/architecture.md
  • docs/code-organization.md
  • internal/agent/agent_context.go
  • internal/agent/context_manager.go
  • internal/agent/lifecycle_init.go
  • internal/agent/loop.go
  • internal/agent/tools.go
  • internal/agent/turn.go
📝 Walkthrough

Walkthrough

The change extracts session wiring into prompt, MCP, and OpenTelemetry helpers. ContextManager now shares mutable LoopState with Loop for messages and compaction data. Compaction callers no longer synchronize duplicate state.

Changes

Session wiring and context management

Layer / File(s) Summary
Extract session initialization helpers
cmd/yaah/wiring.go, cmd/yaah/wiring_mcp.go, cmd/yaah/wiring_otel.go, cmd/yaah/wiring_prompt.go
Session construction delegates MCP startup, OpenTelemetry setup, prompt assembly, and provider instrumentation to helper functions.
Move compaction state into LoopState
internal/agent/context_manager.go
ContextManager stores a shared *LoopState and uses it for messages, token counts, summaries, compaction history, adaptive budgets, cooldowns, trimming, and telemetry.
Connect lifecycle and compaction callers
internal/agent/lifecycle_init.go, internal/agent/agent_context.go, internal/agent/loop.go, internal/agent/tools.go, internal/agent/turn.go
Context manager initialization links the shared state. Loop compaction and trimming paths update LoopState directly.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • buchenberg/yaah#171: Modifies ContextManager and loop state synchronization in the same internal agent areas.
  • buchenberg/yaah#173: Refactors cmd/yaah/wiring.go by extracting agent composition responsibilities.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes both main changes: splitting wiring builders and removing redundant ContextManager state synchronization.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/split-wiring-context-manager

Comment @coderabbitai help to get the list of available commands.

Task #11: Split newAgentSessionWithOptions into focused builders
- wiring_otel.go: initOtel + wrapProviderWithOtel (extracted inline provider wrapping)
- wiring_mcp.go: initMCP (moved to its own file)
- wiring_prompt.go: buildSystemPrompt + buildMainPrompt (extracted inline prompt layers,
  memory enrichment, guidelines, directive injection, and quick-ref assembly)
- wiring.go slimmed from 396 to ~210 lines; removed dead layers.Skills assignment
  (was set after prompts.Build, never read)

Task #12: Complete ContextManager extraction — eliminate state sync dance
- Added State *LoopState pointer to ContextManager; compaction methods now read/write
  mutable state (Messages, PreviousSummary, token counts, compaction tracking) directly
  through the pointer instead of copy-in/copy-out
- Removed 9 duplicate state fields from ContextManager (Messages, PreviousSummary,
  LastPromptTokens, LastCachedPromptTokens, IneffectiveCompactions, LastCompactionTokens,
  CompactionBudgetMultiplier, CompactionSavingsHistory, CompactionForcedByOverflow)
- Eliminated 19-line sync dance in Loop.compactContext and 3-line dance in Loop.trimContext
- Removed redundant CtxMgr.Messages assignments in loop.go, tools.go, turn.go
  (now no-ops since CtxMgr.State points to Loop.State)
- ctxMgr() lazily sets State = &l.State when nil (backward compatible with tests)
@buchenberg
buchenberg force-pushed the feat/split-wiring-context-manager branch from b7cab7d to dea6353 Compare August 7, 2026 02:32

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/yaah/wiring_otel.go`:
- Around line 17-19: Update the OTel enablement logic in the wiring function
around skipOtel and the early return so YAAH_OTEL_ENABLED=true is evaluated
before the disabled-configuration check. Ensure the environment flag can enable
OTel even when cfg.Observability.Otel.Enabled is false and extraOtelProcessors
is empty, while preserving the existing skipOtel behavior.

In `@cmd/yaah/wiring_prompt.go`:
- Around line 13-21: Move the package-level memoryGuidelines constant into the
buildSystemPrompt function scope, or have a helper return its value. Preserve
the existing prompt text and appending behavior while removing the global
declaration.
- Around line 31-72: Move the private prompt-building implementations used by
buildSystemPrompt and buildMainPrompt from cmd/yaah/wiring_prompt.go (lines
31-72) into a focused internal package or file, leaving only command composition
in cmd/yaah and preserving their current behavior and call sites. Apply the same
boundary change to MCP initialization in cmd/yaah/wiring_mcp.go (lines 17-40)
and OTel initialization/provider instrumentation in cmd/yaah/wiring_otel.go
(lines 16-64); each site requires moving its implementation behind internal
while retaining equivalent functionality.

In `@internal/agent/lifecycle_init.go`:
- Around line 51-56: Update the lazy initialization path in ctxMgr() to set
CompactionBudgetMultiplier to 1.0 when initializing CtxMgr.State, ensuring
Loop.Compact has a nonzero preservation budget before applyDefaults() runs.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: eb5705b6-14d9-4440-8b88-c3d7fbdc14a6

📥 Commits

Reviewing files that changed from the base of the PR and between a8d29d5 and b7cab7d.

📒 Files selected for processing (10)
  • cmd/yaah/wiring.go
  • cmd/yaah/wiring_mcp.go
  • cmd/yaah/wiring_otel.go
  • cmd/yaah/wiring_prompt.go
  • internal/agent/agent_context.go
  • internal/agent/context_manager.go
  • internal/agent/lifecycle_init.go
  • internal/agent/loop.go
  • internal/agent/tools.go
  • internal/agent/turn.go
💤 Files with no reviewable changes (1)
  • internal/agent/turn.go

Comment thread cmd/yaah/wiring_otel.go
Comment thread cmd/yaah/wiring_prompt.go Outdated
Comment thread cmd/yaah/wiring_prompt.go
Comment on lines +31 to +72
func buildSystemPrompt(cfg *config.Config, cwd string, db *memory.DB, resumeSessionID string) string {
layers := prompts.Layers{
Identity: prompts.IdentityPrompt,
Environment: prompts.DetectEnvironment(cwd),
UserContext: prompts.LoadUserContext(config.HomeDir()),
Project: instructions.FormatForSystem(instructions.Load(cwd, cwd)),
MaxSubAgentConcurrency: cfg.Agent.SubAgent.MaxConcurrency,
}

if db != nil {
if entries, memErr := db.ListMemory(50); memErr == nil && len(entries) > 0 {
var memLines []string
for _, entry := range entries {
if strings.Contains(entry.Tags, `"user_info"`) {
continue
}
memLines = append(memLines, "- "+entry.Text)
}
if len(memLines) > 0 {
layers.Memory = "You have the following stored information about the user and project:\n" + strings.Join(memLines, "\n")
}
}
}

systemPrompt := prompts.Build(layers)
if db != nil && resumeSessionID == "" {
systemPrompt += memoryGuidelines
}

return systemPrompt
}

// buildMainPrompt derives the top-level agent prompt from the system prompt
// by injecting session directives after the identity block and appending the
// tool quick-reference card. The systemPrompt stays clean so child sub-agent
// prompts never inherit top-level directives.
func buildMainPrompt(cfg *config.Config, systemPrompt string, toolReg *tools.Registry) string {
mainPrompt := prompts.InjectAfterIdentity(systemPrompt, resolveDirectives(cfg))
if quickRef := buildToolQuickRef(toolReg); quickRef != "" {
mainPrompt += "\n\n" + quickRef
}
return mainPrompt

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Move the extracted private builders under internal/.

These new helpers are private implementation code under cmd/yaah. Keep command composition in cmd/yaah and move the implementations to focused internal/ packages or files.

  • cmd/yaah/wiring_prompt.go#L31-L72: move prompt construction behind an internal package boundary.
  • cmd/yaah/wiring_mcp.go#L17-L40: move MCP initialization behind an internal package boundary.
  • cmd/yaah/wiring_otel.go#L16-L64: move OTel initialization and provider instrumentation behind an internal package boundary.
📍 Affects 3 files
  • cmd/yaah/wiring_prompt.go#L31-L72 (this comment)
  • cmd/yaah/wiring_mcp.go#L17-L40
  • cmd/yaah/wiring_otel.go#L16-L64
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/yaah/wiring_prompt.go` around lines 31 - 72, Move the private
prompt-building implementations used by buildSystemPrompt and buildMainPrompt
from cmd/yaah/wiring_prompt.go (lines 31-72) into a focused internal package or
file, leaving only command composition in cmd/yaah and preserving their current
behavior and call sites. Apply the same boundary change to MCP initialization in
cmd/yaah/wiring_mcp.go (lines 17-40) and OTel initialization/provider
instrumentation in cmd/yaah/wiring_otel.go (lines 16-64); each site requires
moving its implementation behind internal while retaining equivalent
functionality.

Source: Coding guidelines

Comment thread internal/agent/lifecycle_init.go
… multiplier init

- wiring_otel.go: evaluate YAAH_OTEL_ENABLED before the early return so
  the env flag can enable OTel when config disables it (pre-existing bug)
- wiring_prompt.go: move memoryGuidelines from package-level const into
  buildSystemPrompt function scope (no globals per AGENTS.md)
- lifecycle_init.go: initialize CompactionBudgetMultiplier=1.0 in ctxMgr()
  lazy path so Loop.Compact has a nonzero preservation budget before
  applyDefaults() runs
Delete plan files for fully-implemented features (max iterations
dialog, TUI-MCP bridge, quiet mode, task pane separation) and the four
ADRs (engine-view separation, middleware pipeline, functional options,
event-driven architecture) whose content is now covered by
docs/architecture.md.

Update doc references across CONTRIBUTING.md, architecture.md, and
code-organization.md to point at architecture.md in place of the
retired ADRs, and fix stale file paths to reflect the recent runner
refactor (cmd/yaah/subagent_runner.go -> internal/agent/runner/).
- Deleted 4 implemented ADRs (0001-0004: engine-view separation, middleware
  pipeline, functional options, event-driven architecture) — all Accepted
  and fully implemented; content covered by architecture.md
- Deleted 5 implemented plan docs from .agents/plans/ (tui-mcp-bridge #159,
  tui-quiet-mode #159, tui2-task-pane-separation #160, max-iterations-dialog,
  web-ui-commands #162) — all features shipped
- Updated docs/adr/README.md and CONTRIBUTING.md to remove dead ADR links
- Fixed stale references to cmd/yaah/subagent_runner.go in architecture.md,
  PROMPT-INJECTION.md, and code-organization.md (now internal/agent/runner)
@buchenberg
buchenberg merged commit 3d61f48 into main Aug 7, 2026
3 of 4 checks passed
@buchenberg
buchenberg deleted the feat/split-wiring-context-manager branch August 7, 2026 02:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant