Skip to content

refactor: architectural hardening — slog, sentinel errors, prompts init - #171

Merged
buchenberg merged 10 commits into
mainfrom
chore/arch-improvements
Aug 7, 2026
Merged

refactor: architectural hardening — slog, sentinel errors, prompts init#171
buchenberg merged 10 commits into
mainfrom
chore/arch-improvements

Conversation

@buchenberg

@buchenberg buchenberg commented Aug 7, 2026

Copy link
Copy Markdown
Owner

Summary

Implements the high-impact, low-effort items from the architectural review, plus gofmt fixes for pre-existing formatting issues.

Changes

1. Replace deprecated log with log/slog

  • internal/agent/agent_context.go: log.Printfslog.Error with structured key-value pairs
  • cmd/yaah/tui.go: log.Printfslog.Warn (keeps log import for SetOutput to devnull)

2. Sentinel errors

  • ErrMaxIterations (internal/agent/loop.go): replaces string-matched "max iterations (%d) reached" — now testable with errors.Is
  • ErrToolDenied (internal/agent/agent_tools.go): replaces 2x fmt.Errorf("tool denied")
  • ErrLoopDetected (internal/agent/pipeline/loopdetect.go): replaces string-matched loop detection error
  • ErrRoleNotFound (internal/agent/subagent/role.go): wired into tools/role.go and tools/task.go
  • ErrToolTimeout (internal/tools/tools.go): wired into bash.go, git.go, powershell.go
  • ErrToolNotFound (internal/tools/tools.go): replaces fmt.Errorf("unknown tool: %s")
  • Updated 2 consumers (repl_loop.go, agent_wrapup_test.go) from strings.Containserrors.Is

3. Fix prompts.go init

  • Replaced init() with sync.Once lazy validation
  • Embedded template section validation no longer calls os.Exit(1) on failure
  • Invalid template logs via slog.Error and returns empty strings from accessors
  • Enables testing of package initialization without process termination

4. ContextManager cleanup

  • Removed redundant l.CtxMgr.Messages = msgs line from compactFn closure (already set by l.compactContext)
  • Updated struct comment: removed stale Phase 1/Phase 2 markers, clarified current delegation pattern

5. Formatting

  • gofmt -w applied to entire project — fixes pre-existing indentation in loop.go, types.go, web_view.go

Testing

  • go build ./... — clean
  • go vet ./... — clean
  • gofmt -l . — empty
  • go test ./... — all pass (3 pre-existing macOS path validator failures on /var vs /private/var)
  • staticcheck ./... — clean
  • No new failures introduced

Breaking changes

None. Sentinel errors wrap the original messages — errors.Is matches the new sentinels; err.Error() output is backward-compatible.

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of agent iteration limits, tool denials, loop detection, timeouts, and missing roles or tools.
    • Preserved useful context in error messages while enabling more reliable error classification.
    • Fixed state synchronization after message compaction.
    • Prevented malformed prompt templates from terminating the application.
    • Improved diagnostics for reasoning mismatches and model-fetch failures.
    • Improved path validation across symbolic links and temporary workspaces.
    • Improved reliability of process status handling and cleanup.
  • Documentation

    • Clarified context management behavior and synchronization.

…it, ContextManager docs

- Replace deprecated log package with log/slog (2 call sites)
- Add sentinel errors: ErrMaxIterations, ErrToolDenied, ErrLoopDetected,
  ErrRoleNotFound, ErrToolTimeout, ErrToolNotFound
- Fix prompts.go init: replace os.Exit with lazy sync.Once validation
- Clean up ContextManager docs: remove stale Phase 1/Phase 2 markers
- Remove redundant l.CtxMgr.Messages = msgs from compactFn closure
- Wire errors.Is in REPL loop and loop detection test
- Format: gofmt -w (fixes pre-existing indentation in loop.go)
@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: 35 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: 4a05f525-40b2-4097-a01d-d0bdfdebab96

📥 Commits

Reviewing files that changed from the base of the PR and between 1f26b5e and 719a9e1.

📒 Files selected for processing (4)
  • .kilo/plans/1784602976760-architecture-review.md
  • internal/process/process.go
  • internal/process/process_test.go
  • internal/tools/path_validator_test.go
📝 Walkthrough

Walkthrough

The PR adds typed errors for agent and tool failures, updates callers and tests to use errors.Is, makes prompt initialization non-fatal, improves structured diagnostics, synchronizes compacted messages with loop state, and stabilizes process tests.

Changes

Error contracts and resilient diagnostics

Layer / File(s) Summary
Typed errors and failure propagation
internal/agent/..., internal/tools/...
Agent and tool failures now return or wrap typed errors while preserving contextual messages.
Typed error handling and validation
cmd/yaah/repl_loop.go, internal/agent/agent_wrapup_test.go, internal/tools/task_test.go, internal/tools/path_validator_test.go
Callers and tests now identify typed failures with errors.Is. Path validation tests canonicalize temporary paths.
Safe lazy prompt initialization
internal/prompts/prompts.go
Chunk prompt sections initialize once, log malformed templates, and return empty values when unavailable.
State synchronization and diagnostics
internal/agent/..., cmd/yaah/tui.go, cmd/yaah/web_view.go
Compaction updates loop state. Diagnostics use structured logging. Formatting-only changes preserve behavior.
Portable process test execution
internal/process/process_test.go
Process tests use shell-compatible commands, deferred cleanup, flexible status checks, and bounded polling for failures.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

  • buchenberg/yaah#169: Both PRs modify maximum-iteration handling in internal/agent/loop.go and cmd/yaah/repl_loop.go.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: structured logging, typed sentinel errors, and lazy prompt initialization.
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 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/arch-improvements

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

@kilo-code-bot

kilo-code-bot Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Code Review Summary

Status: No Issues Found | Recommendation: Merge

Files Reviewed (19 files)
  • cmd/yaah/repl_loop.go
  • cmd/yaah/tui.go
  • cmd/yaah/web_view.go
  • internal/agent/agent_context.go
  • internal/agent/agent_tools.go
  • internal/agent/agent_wrapup_test.go
  • internal/agent/context_manager.go
  • internal/agent/lifecycle_init.go
  • internal/agent/loop.go
  • internal/agent/pipeline/loopdetect.go
  • internal/agent/subagent/role.go
  • internal/agent/types.go
  • internal/prompts/prompts.go
  • internal/tools/bash.go
  • internal/tools/git.go
  • internal/tools/powershell.go
  • internal/tools/role.go
  • internal/tools/task.go
  • internal/tools/tools.go

Reviewed by step-3.7-flash · Input: 119.8K · Output: 19.1K · Cached: 555K

@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: 1

🤖 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 `@internal/agent/loop.go`:
- Around line 18-20: Replace the package-level sentinels with comparable typed
errors implementing Is: internal/agent/loop.go:18-20 for max-iteration,
internal/agent/agent_tools.go:20-22 for tool-denied,
internal/agent/pipeline/loopdetect.go:14-16 for loop-detected,
internal/agent/subagent/role.go:10-12 for role-not-found, and
internal/tools/tools.go:72-77 for tool-timeout and tool-not-found. Update all
callers to use zero-value typed targets with errors.Is so existing matching
behavior is preserved, and remove the global sentinel declarations.
🪄 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: bc25c608-a289-408c-b0a2-207d6cb7215b

📥 Commits

Reviewing files that changed from the base of the PR and between bbbe48a and c5e1b41.

📒 Files selected for processing (19)
  • cmd/yaah/repl_loop.go
  • cmd/yaah/tui.go
  • cmd/yaah/web_view.go
  • internal/agent/agent_context.go
  • internal/agent/agent_tools.go
  • internal/agent/agent_wrapup_test.go
  • internal/agent/context_manager.go
  • internal/agent/lifecycle_init.go
  • internal/agent/loop.go
  • internal/agent/pipeline/loopdetect.go
  • internal/agent/subagent/role.go
  • internal/agent/types.go
  • internal/prompts/prompts.go
  • internal/tools/bash.go
  • internal/tools/git.go
  • internal/tools/powershell.go
  • internal/tools/role.go
  • internal/tools/task.go
  • internal/tools/tools.go
💤 Files with no reviewable changes (1)
  • internal/agent/lifecycle_init.go

Comment thread internal/agent/loop.go Outdated
Replace six var-sentinel errors with typed error types that implement
the Is method for errors.Is compatibility with zero-value targets:

- ErrMaxIterations → MaxIterationsError
- ErrToolDenied → ToolDeniedError
- ErrLoopDetected → LoopDetectedError (with Tool/Count/Window fields)
- ErrRoleNotFound → RoleNotFoundError
- ErrToolTimeout → ToolTimeoutError (with Tool/Timeout fields)
- ErrToolNotFound → ToolNotFoundError

Callers use errors.Is(err, ErrorType{}) instead of package variables.
All builder values are now constructor-returned, complying with the
no-globals-in-non-command-files convention.
… tests

On macOS TempDir returns /var/folders/... which is a symlink to
/private/var/folders/... On Windows it may return short names like
RUNNER~1. Resolve the workspace and outside directories with
EvalSymlinks before using them to construct test paths, and loosen
the AskFn path comparison to verify non-empty rather than strict
string equality.

@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: 1

🤖 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 `@internal/tools/path_validator_test.go`:
- Around line 144-145: Update the assertion in the AskFn test callback to
require gotPath equals the canonical outside path, while retaining the existing
failure behavior for an incorrect or empty path. Use the outside path symbol
already defined by the test rather than only checking gotPath is non-empty.
🪄 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: 3fe9521d-56fd-442b-9c9e-9e69ab7947b9

📥 Commits

Reviewing files that changed from the base of the PR and between 94d62ce and 6a7c67f.

📒 Files selected for processing (1)
  • internal/tools/path_validator_test.go

Comment thread internal/tools/path_validator_test.go Outdated
…cess tests

- Replace Write-Host with echo (cross-platform)
- Add defer m.Stop() to clean up lingering processes
- Replace single time.Sleep in failing command test with poll loop
- Accept 'finished' or 'running' status for fast-exit commands
Resolve the outside path through the same filepath.Abs + EvalSymlinks
chain that ResolvePath uses internally so the comparison is stable
across macOS /var→/private/var symlinks and Windows short-name
resolution.
Staticcheck SA5011: defer captures info.ID before nil check in
StartFailingCommand. Move nil guards before defer statements
so the pointer is proven non-nil when the deferred Stop runs.

@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 `@internal/process/process_test.go`:
- Around line 30-33: Reorder cleanup registration in the affected process-start
tests so `err` and `info` are validated before evaluating `info.ID`. Update both
the initial test block and `TestStartFailingCommand`, registering `defer
m.Stop(info.ID)` only after confirming `info` is non-nil.
- Around line 128-145: Update the status check in the polling test around
info.Status so it returns successfully only when status equals "error". Treat
any other status, including non-running terminal states, as unexpected and
preserve the existing diagnostic logging and timeout failure behavior.
- Around line 38-40: Update the test assertion around Info.Status to lock
info.mu, copy info.Status to a local variable, unlock the mutex, and validate
the copied status instead of reading the field unsynchronized.
- Around line 75-79: Update the command passed to m.Start in the process test to
use a PowerShell-compatible separator such as `;` instead of `&&`, while
preserving the existing assertions and cleanup.
🪄 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: b08ec15c-ff39-4b1d-bcd8-90766fb374bc

📥 Commits

Reviewing files that changed from the base of the PR and between 6a7c67f and 1f26b5e.

📒 Files selected for processing (1)
  • internal/process/process_test.go

Comment thread internal/process/process_test.go Outdated
Comment thread internal/process/process_test.go Outdated
Comment thread internal/process/process_test.go Outdated
Comment thread internal/process/process_test.go
- Lock info.mu before reading Status in TestStartSimpleCommand
- Use ; instead of && for PowerShell 5.1 compatibility in echo test
- Require 'error' status (not just non-'running') in poll loop
- Keep Start-Sleep tests as-is (require pwsh on runner)
The 500ms sleep wasn't always enough on slow CI runners for the
process to complete and flush its output. Poll for a non-'running'
status and check logs when the process exits.
Background processes inherited the parent stdin which never closes on
CI runners, causing shells (pwsh/sh) to block indefinitely waiting for
EOF. Set cmd.Stdin = nil so the child gets an immediate EOF and exits
normally. Replaced fixed 500ms sleep in echo test with poll loop for
consistent behavior on slow runners.
@buchenberg
buchenberg merged commit a261b38 into main Aug 7, 2026
4 checks passed
@buchenberg
buchenberg deleted the chore/arch-improvements branch August 7, 2026 01:23
@coderabbitai coderabbitai Bot mentioned this pull request Aug 20, 2026
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