feat(autonomy): task-tier routing, Ollama fleet, health/fallback, and safety - #1921
alanoliveira2025 wants to merge 10 commits into
Conversation
Add an autonomy layer that classifies prompt complexity and routes agents via taskRouting when enabled, with modes smart/fast/code/quality/fixed. Legacy agentRouting is unchanged when autonomy is off.
Track provider latency/errors, skip unhealthy models at select time, and advance the fallback chain on live connection/5xx failures inside withRetry. Adds doctor:autonomy for local diagnostics.
Stop runaway agent turns when the same tool error repeats, edits make no file changes, or OPENCLAUDE_MAX_TOOLS_PER_TURN is exceeded. Wired into runTools; effort hints already map from task tier in routePolicy.
…ncy suite Close the main-thread gap so autonomy applies beyond subagents, add local turn telemetry and session insights, expose /route for operators, and ship integration tests that lock professional routing contracts.
Wire the installed Ollama models into taskRouting/fallbacks, default start-ollama to smart mode, and add autonomy:ollama to reapply policy.
Share circuit observation via circuitToolBridge, enforce breakers in StreamingToolExecutor, and prefer providerOverride.effort over AppState effort for API calls without thrashing the UI.
📝 WalkthroughWalkthroughAdds an autonomy layer for task-tier routing, provider health/fallback, circuit breakers, telemetry/session insights, context budget masking, and related CLI/docs wiring. Also adds a Portuguese user guide, knowledge-base notes, and phase/design documents for the rollout. ChangesAutonomy Feature Implementation
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 5 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
⚔️ Resolve merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Enable content-replacement budgets when autonomy is on (open builds lack GrowthBook hawthorn flags). Use tighter 20k/80k caps so Ollama sessions persist oversized Bash/Grep dumps instead of burning context.
Document Phase 6 (not implemented) and mark the testing pause for Phases 1-5 so operators can validate Ollama autonomy without new code.
There was a problem hiding this comment.
Actionable comments posted: 19
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/screens/REPL.tsx (1)
2416-2453: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy liftAutonomy resolution + telemetry fire on every
getToolUseContextcall, not once per turn.
getToolUseContextis called from many sites (onQueryImpl, handleBackgroundQuery, immediate/queued commands, onAgentSubmit, and inline in render fortoolPermissionOverlayat line 4537). Each call re-runsresolveAutonomyForMessageswithrecordTelemetry: true, so:
- Settings load + heuristic classification re-runs synchronously on every REPL re-render while a permission dialog is showing (not just once at submit time).
- A
route_selecttelemetry line gets appended toturns.jsonlfor every such call that resolves an override — polluting the session-insights data this PR is designed to produce, not just logging actual dispatched requests.Consider computing the autonomy override once per turn (e.g. memoize by message count/last uuid, or thread a precomputed override through
getToolUseContextcallers) and only passrecordTelemetry: truefrom the actual dispatch path (onQueryImpl), not from incidental context builds used for permission UI, background-session setup, etc.🤖 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 `@src/screens/REPL.tsx` around lines 2416 - 2453, `getToolUseContext` is recalculating autonomy and emitting telemetry on every call, which causes repeated `resolveAutonomyForMessages` work and duplicate `route_select` entries. Update `REPL.tsx` so the autonomy override is computed once per turn (for example by memoizing on the current message set or passing a precomputed value through callers like `onQueryImpl`, `handleBackgroundQuery`, and the permission UI path), and reserve `recordTelemetry: true` for the actual dispatch flow rather than incidental context builds.
🤖 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 `@docs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.md`:
- Line 8: The setup instruction currently uses a machine-specific absolute
Windows path, which breaks portability. Update the command in the STOP-AND-TEST
guidance to use a generic relative or placeholder repo path instead of
E:\Agente_OpenClaude, and keep the wording reusable for contributors on any OS.
Refer to the path example in the markdown and replace it with a neutral
instruction like changing into the OpenClaude repository directory.
In `@GUIA_USO.md`:
- Around line 270-289: The “Trocar Modelo na Hora” section in GUIA_USO.md
contains stray editing artifacts that should be cleaned up. Remove the
standalone `ollama run kimi-k2.6:nuvem` command if it is not meant to be part of
the section, replace the placeholder `ESTA` with the intended content or delete
it from the fenced block, and change the heading that embeds `.\start-ollama.ps1
-Model "kimi-k2.6:cloud"` into a proper descriptive heading with the command
moved into its own code block.
- Around line 20-24: Update the runtime requirements table in GUIA_USO.md so the
Node.js minimum version matches AGENTS.md and the installed CLI requirement;
change the Node.js entry from 20+ to >=22.0.0. Keep the rest of the table
unchanged and verify the “Verificar” command still reflects the intended version
check.
In `@package.json`:
- Line 16: Revert the package.json scripts for dev, start, and smoke back to
running the CLI under Node instead of bun, since the current changes in the
dev/start/smoke entries switch the runtime away from the supported Node.js
workflow. Update those script definitions in package.json to use the Node-based
CLI invocation already used by the project, and keep the existing build step
intact so the scripts continue to exercise the built CLI under Node.
In `@scripts/apply-ollama-autonomy.ts`:
- Line 92: The profile file path in applyOllamaAutonomy is being derived from
process.cwd(), which can place .openclaude-profile.json outside the expected
repo location. Update the path construction in the profilePath assignment to
resolve relative to the script/repo location instead of the current working
directory, or add a warning that clearly calls out the absolute path before
writing. Keep the existing path display behavior in applyOllamaAutonomy so users
can see where the file will be written.
- Around line 33-34: Wrap the JSON.parse call in the settings-loading flow so
corrupted or empty settings files produce a clear actionable message instead of
an uncaught stack trace. In the code that reads settingsPath and parses raw into
settings, add a try/catch around JSON.parse, and on failure surface a
descriptive error that mentions the settings file could not be parsed and
suggests checking ~/.claude/settings.json for corruption or emptiness. Keep the
behavior localized to the settings parsing logic in apply-ollama-autonomy.ts.
In `@scripts/doctor-autonomy.ts`:
- Around line 68-72: The probe loop in settings.agentModels currently lets a
single probeAndUpdate failure abort the whole doctor-autonomy flow. Update the
loop in the probeAndUpdate call path to wrap each model probe in its own
try/catch, so one model’s network/auth/URL error is recorded and the loop
continues for the remaining models. Keep the change localized around doProbe,
settings.agentModels, and probeAndUpdate, and make sure failures are surfaced in
the health report/logs instead of throwing out of the script.
In `@src/commands/route/route.ts`:
- Around line 11-17: The /route command currently lets failures from
readRecentTelemetry and listInsightFiles bubble up and crash the command. Update
call in route.ts to wrap the async service calls in a try/catch, and use a safe
fallback when telemetry/insight loading fails so the command can still return
the other route data. Keep the existing flow around getInitialSettings,
isAutonomyEnabled, resolveAutonomyMode, and getHealthSnapshot intact, but make
the readRecentTelemetry/listInsightFiles portion degrade gracefully and log or
surface the error without throwing.
In `@src/services/api/agentRouting.test.ts`:
- Around line 125-182: These autonomy routing tests are leaking global state,
which can make `resolveAgentProvider` pick the wrong model. Add test setup in
`agentRouting.test.ts` to clear `process.env.OPENCLAUDE_AUTONOMY` and call
`resetHealthRegistryForTests()` before each case (or equivalent local setup) so
the autonomy-enabled scenarios are isolated from prior health/autonomy state.
In `@src/services/api/claude.ts`:
- Around line 926-946: The failover callback logic in `tryProviderFailover` and
`onProviderSuccess` is duplicated between the non-streaming and streaming paths
in `claude.ts`. Extract this shared behavior into a helper that builds or
returns both callbacks, and reuse it in both call sites so the
`advanceFallbackOnFailure`, `recordProviderSuccess`, and
`activeProviderOverride` handling stays in sync.
In `@src/services/autonomy/circuitToolBridge.test.ts`:
- Around line 44-64: The circuit breaker tests in circuitToolBridge.test.ts only
cover error streaks; add coverage for the noop edit path and the disabled
autonomy state. Extend extractToolObservation tests to verify a successful tool
result that matches the noop regex is classified as a noop observation, and add
a createToolCircuitSession test with OPENCLAUDE_AUTONOMY=0 that asserts the
session is null/disabled. Use the existing createToolCircuitSession,
extractToolObservation, observeToolMessage, and toolResultMsg helpers to keep
the new cases consistent with the current suite.
In `@src/services/autonomy/circuitToolBridge.ts`:
- Around line 66-73: The noop edit detection in circuitToolBridge should stop
hardcoding tool names and use the shared edit-tool check instead. Update the
logic in circuitToolBridge to import and call isEditTool() from
circuitBreakers.ts for the toolName check, so it stays aligned with EDIT_TOOLS
and includes FileEdit/FileWrite automatically. Keep the existing resultText
regex check, but gate it behind isEditTool(toolName) rather than comparing
against individual strings.
In `@src/services/autonomy/providerFallback.ts`:
- Around line 108-128: The fallback chain handling is using case-sensitive model
comparisons, which can leave the selected candidate in the chain and allow the
same model to be reselected on the next failover. Update applyHealthSelection
and advanceFallbackOnFailure to compare model identifiers case-insensitively or
via a normalized form, and when rebuilding fallbackChain filter out the chosen
candidate using the original candidate value rather than cfg.name so matching
works regardless of casing. Ensure the skip check against override.model uses
the same normalized comparison logic everywhere these fallback candidates are
selected.
In `@src/services/autonomy/resolveForMessages.ts`:
- Around line 55-95: resolveAutonomyForMessages currently has no safety net, so
errors from getInitialSettings, isAutonomyEnabled, or resolveAgentProvider can
bubble into REPL render and AgentTool paths. Wrap the body of
resolveAutonomyForMessages in defensive error handling and return null on
failure, keeping the routing feature non-fatal; use the existing
resolveAutonomyForMessages and resolveAgentProvider entry points as the place to
apply the guard, similar to the fail-closed posture used in telemetry.ts.
- Around line 64-67: The current “last user turn only” logic in
resolveForMessages is using extractUserTextFromMessages plus a line-based slice,
which can mix multiple turns and multi-line content. Update the classification
input so it selects the actual last user message/turn from input.messages rather
than truncating the joined user text, and keep the hasImage check unchanged. Use
the existing resolveForMessages and extractUserTextFromMessages flow as the
entry point, but make the turn selection explicit and turn-based so the comment
matches the implementation.
In `@src/services/autonomy/routePolicy.ts`:
- Around line 50-56: `isAutonomyEnabled` treats OPENCLAUDE_AUTONOMY as disabled
only for "0", which is inconsistent with the autonomy check used elsewhere.
Update the environment handling in `isAutonomyEnabled` to also return false when
OPENCLAUDE_AUTONOMY is set to "false", keeping it aligned with the logic in
`doctor-autonomy.ts` and preventing fallback to settings when the env var
explicitly disables autonomy.
In `@src/services/autonomy/taskSignals.ts`:
- Around line 33-34: The VISION_RE pattern in taskSignals.ts is too broad
because it matches the common coding term “print,” which causes
classifyComplexity to route ordinary CLI prompts to vision first. Update
VISION_RE to remove the standalone print token or narrow it to a
screenshot-specific phrase such as printscreen/print screen, while keeping the
existing vision-related terms intact so taskRouting.vision only triggers on
actual visual requests.
In `@src/services/autonomy/telemetry.ts`:
- Around line 89-109: `readRecentTelemetry` currently loads the entire
`turns.jsonl` file into memory on every call, so the telemetry log can grow
without bound and make `/route` and `doctor:autonomy` progressively slower.
Update the telemetry write/read flow in `readRecentTelemetry` and the related
append path in this module to enforce a bounded history, such as
truncating/rotating to the last N lines when the file exceeds a size threshold,
instead of relying on callers’ `limit`. Also remove the inline `await
import('fs/promises')` in `readRecentTelemetry` by using the existing static
imports from that module and adding `readFile` alongside them.
In `@start-ollama.ps1`:
- Around line 1-15: The PowerShell launch script contains non-ASCII usage text
but is saved without a UTF-8 BOM, so update start-ollama.ps1 to be encoded as
UTF-8 with BOM. Preserve the existing comment content and ensure the file is
re-saved with BOM so PowerShell reads the arrows and other Unicode characters
correctly, addressing the PSUseBOMForUnicodeEncodedFile warning.
---
Outside diff comments:
In `@src/screens/REPL.tsx`:
- Around line 2416-2453: `getToolUseContext` is recalculating autonomy and
emitting telemetry on every call, which causes repeated
`resolveAutonomyForMessages` work and duplicate `route_select` entries. Update
`REPL.tsx` so the autonomy override is computed once per turn (for example by
memoizing on the current message set or passing a precomputed value through
callers like `onQueryImpl`, `handleBackgroundQuery`, and the permission UI
path), and reserve `recordTelemetry: true` for the actual dispatch flow rather
than incidental context builds.
🪄 Autofix (Beta)
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: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 4d9f2dbe-6a55-48f6-9d42-1593dc9e39ae
📒 Files selected for processing (55)
GUIA_USO.mddocs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.mddocs/superpowers/knowledge/2026-07-09-consistency-eval.mddocs/superpowers/knowledge/2026-07-09-ollama-first-fleet.mddocs/superpowers/knowledge/2026-07-09-phase1-shipped.mddocs/superpowers/knowledge/2026-07-09-phase2-health-fallback.mddocs/superpowers/knowledge/2026-07-09-phase5-context-budget.mddocs/superpowers/knowledge/README.mddocs/superpowers/knowledge/ROUTING_BASELINE.mddocs/superpowers/knowledge/SESSION_INSIGHTS_TEMPLATE.mddocs/superpowers/plans/2026-07-09-agent-performance-autonomy.mddocs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.mddocs/superpowers/specs/2026-07-09-phase6-hybrid-local-intelligence.mdpackage.jsonscripts/apply-ollama-autonomy.tsscripts/doctor-autonomy.tssrc/Tool.tssrc/commands.tssrc/commands/route/index.tssrc/commands/route/route.tssrc/query.tssrc/query/stopHooks.tssrc/screens/REPL.tsxsrc/services/api/agentRouting.test.tssrc/services/api/agentRouting.tssrc/services/api/claude.tssrc/services/api/withRetry.tssrc/services/autonomy/circuitBreakers.test.tssrc/services/autonomy/circuitBreakers.tssrc/services/autonomy/circuitToolBridge.test.tssrc/services/autonomy/circuitToolBridge.tssrc/services/autonomy/complexityClassifier.test.tssrc/services/autonomy/complexityClassifier.tssrc/services/autonomy/consistency.integration.test.tssrc/services/autonomy/contextBudget.test.tssrc/services/autonomy/contextBudget.tssrc/services/autonomy/index.tssrc/services/autonomy/providerFallback.test.tssrc/services/autonomy/providerFallback.tssrc/services/autonomy/providerHealth.test.tssrc/services/autonomy/providerHealth.tssrc/services/autonomy/resolveForMessages.test.tssrc/services/autonomy/resolveForMessages.tssrc/services/autonomy/routePolicy.test.tssrc/services/autonomy/routePolicy.tssrc/services/autonomy/sessionInsights.tssrc/services/autonomy/taskSignals.tssrc/services/autonomy/telemetry.test.tssrc/services/autonomy/telemetry.tssrc/services/tools/StreamingToolExecutor.tssrc/services/tools/toolOrchestration.tssrc/tools/AgentTool/runAgent.tssrc/utils/settings/types.tssrc/utils/toolResultStorage.tsstart-ollama.ps1
📜 Review details
🧰 Additional context used
📓 Path-based instructions (8)
**
⚙️ CodeRabbit configuration file
**: # AGENTS.md - AI Agent Coding GuideThis guide is for AI coding agents working in the OpenClaude repository. Read it before changing code, and also follow CONTRIBUTING.md for contributor policy, PR expectations, review follow-up, and project scope.
Project Snapshot
OpenClaude is a coding-agent CLI for cloud and local model providers. It supports OpenAI-compatible APIs, Anthropic, Gemini, DeepSeek, Ollama, MCP, local backends, slash commands, tools, agents, and a React/Ink terminal UI.
The installed CLI runs on Node.js
>=22.0.0. Bun is used for source builds, scripts, dependency management, and tests.Work Style
- Keep changes focused on one problem.
- Prefer existing patterns in the file or nearby module.
- Avoid unrelated formatting, renames, dependency changes, or broad rewrites.
- Add or update tests when behavior changes.
- Update docs when setup, commands, provider behavior, or user-facing behavior changes.
- For new features, larger refactors, dependencies, or runtime changes, follow the issue-first guidance in CONTRIBUTING.md.
Stack And Conventions
- TypeScript with strict mode and ESM imports.
- React + Ink for terminal UI.
- Bun lockfile and Bun scripts for development workflows.
- Node runtime for the built CLI.
Common libraries and patterns:
chalkfor terminal color.commanderfor CLI argument parsing.execafor child processes.- Existing service, provider, settings, permission, and UI patterns over new abstractions.
Repository Map
src/commands/- slash and CLI command implementations.src/components/- React/Ink UI components.src/services/- API, MCP, OAuth, wiki, voice, and other service integrations.src/tools/- tool implementations.src/utils/- shared utilities.src/integrations/- provider and model integration metadata.src/entrypoints/- CLI, MCP, SDK, and generated public types.src/tasks/- local, remote, workflow, and monitor tas...
Files:
docs/superpowers/knowledge/SESSION_INSIGHTS_TEMPLATE.mdsrc/services/autonomy/complexityClassifier.test.tsdocs/superpowers/knowledge/2026-07-09-consistency-eval.mddocs/superpowers/knowledge/2026-07-09-ollama-first-fleet.mddocs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.mdsrc/services/autonomy/circuitBreakers.test.tssrc/services/autonomy/resolveForMessages.test.tsscripts/doctor-autonomy.tsdocs/superpowers/knowledge/2026-07-09-phase5-context-budget.mdsrc/commands.tssrc/services/autonomy/providerHealth.test.tssrc/query.tssrc/services/autonomy/providerFallback.test.tssrc/query/stopHooks.tsdocs/superpowers/knowledge/README.mddocs/superpowers/knowledge/2026-07-09-phase2-health-fallback.mddocs/superpowers/knowledge/2026-07-09-phase1-shipped.mdsrc/services/autonomy/circuitToolBridge.test.tssrc/tools/AgentTool/runAgent.tssrc/Tool.tssrc/services/autonomy/telemetry.test.tssrc/services/autonomy/routePolicy.test.tspackage.jsonsrc/services/api/agentRouting.test.tssrc/services/autonomy/taskSignals.tsdocs/superpowers/knowledge/ROUTING_BASELINE.mdsrc/commands/route/route.tssrc/utils/settings/types.tssrc/services/autonomy/circuitBreakers.tssrc/services/autonomy/sessionInsights.tssrc/commands/route/index.tssrc/services/autonomy/index.tsdocs/superpowers/plans/2026-07-09-agent-performance-autonomy.mdsrc/services/autonomy/complexityClassifier.tssrc/services/autonomy/contextBudget.test.tssrc/services/autonomy/resolveForMessages.tssrc/screens/REPL.tsxscripts/apply-ollama-autonomy.tssrc/services/tools/toolOrchestration.tssrc/utils/toolResultStorage.tssrc/services/api/claude.tsstart-ollama.ps1src/services/autonomy/contextBudget.tssrc/services/api/agentRouting.tssrc/services/api/withRetry.tsdocs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.mddocs/superpowers/specs/2026-07-09-phase6-hybrid-local-intelligence.mdsrc/services/autonomy/routePolicy.tssrc/services/autonomy/consistency.integration.test.tssrc/services/autonomy/providerFallback.tsGUIA_USO.mdsrc/services/autonomy/providerHealth.tssrc/services/tools/StreamingToolExecutor.tssrc/services/autonomy/telemetry.tssrc/services/autonomy/circuitToolBridge.ts
**/*
⚙️ CodeRabbit configuration file
**/*: Apply the OpenClaude maintainer review rubric from AGENTS.md. Review the current diff, not stale discussion context. Separate real blockers from suggestions. Do not request changes for vague style churn. Treat approval as merge-ready from CodeRabbit's side, pending required human review and GitHub Checks. If checks are failing or unavailable, say so clearly instead of implying the PR is fully ready.
Files:
docs/superpowers/knowledge/SESSION_INSIGHTS_TEMPLATE.mdsrc/services/autonomy/complexityClassifier.test.tsdocs/superpowers/knowledge/2026-07-09-consistency-eval.mddocs/superpowers/knowledge/2026-07-09-ollama-first-fleet.mddocs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.mdsrc/services/autonomy/circuitBreakers.test.tssrc/services/autonomy/resolveForMessages.test.tsscripts/doctor-autonomy.tsdocs/superpowers/knowledge/2026-07-09-phase5-context-budget.mdsrc/commands.tssrc/services/autonomy/providerHealth.test.tssrc/query.tssrc/services/autonomy/providerFallback.test.tssrc/query/stopHooks.tsdocs/superpowers/knowledge/README.mddocs/superpowers/knowledge/2026-07-09-phase2-health-fallback.mddocs/superpowers/knowledge/2026-07-09-phase1-shipped.mdsrc/services/autonomy/circuitToolBridge.test.tssrc/tools/AgentTool/runAgent.tssrc/Tool.tssrc/services/autonomy/telemetry.test.tssrc/services/autonomy/routePolicy.test.tspackage.jsonsrc/services/api/agentRouting.test.tssrc/services/autonomy/taskSignals.tsdocs/superpowers/knowledge/ROUTING_BASELINE.mdsrc/commands/route/route.tssrc/utils/settings/types.tssrc/services/autonomy/circuitBreakers.tssrc/services/autonomy/sessionInsights.tssrc/commands/route/index.tssrc/services/autonomy/index.tsdocs/superpowers/plans/2026-07-09-agent-performance-autonomy.mdsrc/services/autonomy/complexityClassifier.tssrc/services/autonomy/contextBudget.test.tssrc/services/autonomy/resolveForMessages.tssrc/screens/REPL.tsxscripts/apply-ollama-autonomy.tssrc/services/tools/toolOrchestration.tssrc/utils/toolResultStorage.tssrc/services/api/claude.tsstart-ollama.ps1src/services/autonomy/contextBudget.tssrc/services/api/agentRouting.tssrc/services/api/withRetry.tsdocs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.mddocs/superpowers/specs/2026-07-09-phase6-hybrid-local-intelligence.mdsrc/services/autonomy/routePolicy.tssrc/services/autonomy/consistency.integration.test.tssrc/services/autonomy/providerFallback.tsGUIA_USO.mdsrc/services/autonomy/providerHealth.tssrc/services/tools/StreamingToolExecutor.tssrc/services/autonomy/telemetry.tssrc/services/autonomy/circuitToolBridge.ts
{README.md,CONTRIBUTING.md,docs/**,.github/pull_request_template.md}
⚙️ CodeRabbit configuration file
{README.md,CONTRIBUTING.md,docs/**,.github/pull_request_template.md}: Review docs for accuracy against current code behavior. Flag security or provider claims that overpromise, stale install commands, missing setup caveats, and instructions that could push users toward unsafe credential handling. Keep purely wording-level suggestions non-blocking.
Files:
docs/superpowers/knowledge/SESSION_INSIGHTS_TEMPLATE.mddocs/superpowers/knowledge/2026-07-09-consistency-eval.mddocs/superpowers/knowledge/2026-07-09-ollama-first-fleet.mddocs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.mddocs/superpowers/knowledge/2026-07-09-phase5-context-budget.mddocs/superpowers/knowledge/README.mddocs/superpowers/knowledge/2026-07-09-phase2-health-fallback.mddocs/superpowers/knowledge/2026-07-09-phase1-shipped.mddocs/superpowers/knowledge/ROUTING_BASELINE.mddocs/superpowers/plans/2026-07-09-agent-performance-autonomy.mddocs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.mddocs/superpowers/specs/2026-07-09-phase6-hybrid-local-intelligence.md
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
TypeScript code in this repository must use strict mode and ESM imports.
Files:
src/services/autonomy/complexityClassifier.test.tssrc/services/autonomy/circuitBreakers.test.tssrc/services/autonomy/resolveForMessages.test.tsscripts/doctor-autonomy.tssrc/commands.tssrc/services/autonomy/providerHealth.test.tssrc/query.tssrc/services/autonomy/providerFallback.test.tssrc/query/stopHooks.tssrc/services/autonomy/circuitToolBridge.test.tssrc/tools/AgentTool/runAgent.tssrc/Tool.tssrc/services/autonomy/telemetry.test.tssrc/services/autonomy/routePolicy.test.tssrc/services/api/agentRouting.test.tssrc/services/autonomy/taskSignals.tssrc/commands/route/route.tssrc/utils/settings/types.tssrc/services/autonomy/circuitBreakers.tssrc/services/autonomy/sessionInsights.tssrc/commands/route/index.tssrc/services/autonomy/index.tssrc/services/autonomy/complexityClassifier.tssrc/services/autonomy/contextBudget.test.tssrc/services/autonomy/resolveForMessages.tssrc/screens/REPL.tsxscripts/apply-ollama-autonomy.tssrc/services/tools/toolOrchestration.tssrc/utils/toolResultStorage.tssrc/services/api/claude.tssrc/services/autonomy/contextBudget.tssrc/services/api/agentRouting.tssrc/services/api/withRetry.tssrc/services/autonomy/routePolicy.tssrc/services/autonomy/consistency.integration.test.tssrc/services/autonomy/providerFallback.tssrc/services/autonomy/providerHealth.tssrc/services/tools/StreamingToolExecutor.tssrc/services/autonomy/telemetry.tssrc/services/autonomy/circuitToolBridge.ts
{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}
⚙️ CodeRabbit configuration file
{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}: Review tests for meaningful coverage of the changed behavior, isolation of global/env/config state, async cleanup, fake timers, provider profile leaks, and Windows-compatible assumptions. Block when risky runtime changes lack focused regression coverage or tests assert implementation details while missing the user-visible behavior.
Files:
src/services/autonomy/complexityClassifier.test.tssrc/services/autonomy/circuitBreakers.test.tssrc/services/autonomy/resolveForMessages.test.tssrc/services/autonomy/providerHealth.test.tssrc/services/autonomy/providerFallback.test.tssrc/services/autonomy/circuitToolBridge.test.tssrc/services/autonomy/telemetry.test.tssrc/services/autonomy/routePolicy.test.tssrc/services/api/agentRouting.test.tssrc/services/autonomy/contextBudget.test.tssrc/services/autonomy/consistency.integration.test.ts
{bin/**,scripts/**,package.json,src/setup.ts,src/main.tsx,src/entrypoints/**}
⚙️ CodeRabbit configuration file
{bin/**,scripts/**,package.json,src/setup.ts,src/main.tsx,src/entrypoints/**}: Review install, launcher, build, packaging, startup, and entrypoint changes for cross-platform compatibility, tracked-source rewrites, env/config precedence, and release safety. Block on changes that can break Windows/macOS/Linux startup or publish unexpected artifacts.
Files:
scripts/doctor-autonomy.tspackage.jsonscripts/apply-ollama-autonomy.ts
src/{components/permissions,utils/permissions,hooks/toolPermission,tools,entrypoints/sdk}/**
⚙️ CodeRabbit configuration file
src/{components/permissions,utils/permissions,hooks/toolPermission,tools,entrypoints/sdk}/**: Review permission prompts, auto-allow logic, sandbox behavior, SDK permission schemas, shell/PowerShell execution, and background execution paths as security-sensitive. Block on bypasses, unclear trust boundaries, unsafe path handling, missing user visibility, or changes that broaden allowed behavior without an explicit maintainer decision.
Files:
src/tools/AgentTool/runAgent.ts
{src/services/api/**,src/integrations/**,src/utils/model/**,src/utils/provider*.ts,src/commands/provider/**}
⚙️ CodeRabbit configuration file
{src/services/api/**,src/integrations/**,src/utils/model/**,src/utils/provider*.ts,src/commands/provider/**}: Review provider routing, model selection, env precedence, auth/token handling, OpenAI-compatible shims, retries, proxy behavior, and outbound HTTP behavior with high scrutiny. Block on silent default changes, hidden fallback expansion, credential reuse mistakes, hardcoded provider assumptions, or new network reach that is not intentional and documented.
Files:
src/services/api/agentRouting.test.tssrc/services/api/claude.tssrc/services/api/agentRouting.tssrc/services/api/withRetry.ts
🪛 LanguageTool
docs/superpowers/knowledge/SESSION_INSIGHTS_TEMPLATE.md
[locale-violation] ~1-1: “TEMPLATE” é um estrangeirismo. É preferível dizer “modelo”./.openclaude/insights/<s...
Context: # Session Insight — TEMPLATE Copiar para `
(PT_BARBARISMS_REPLACE_TEMPLATE)
docs/superpowers/knowledge/2026-07-09-consistency-eval.md
[grammar] ~55-~55: Ensure spelling is correct
Context: ...gex — sub-ms ## Quality bar for “app profissional” Met: deterministic policy, failover prov...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
docs/superpowers/knowledge/2026-07-09-phase5-context-budget.md
[locale-violation] ~1-~1: “budget” é um estrangeirismo. É preferível dizer “orçamento” ou “verba”.
Context: # 2026-07-09 — Phase 5 context budget Ação: Ativar masking de tool resul...
(PT_BARBARISMS_REPLACE_BUDGET)
[uncategorized] ~3-~3: Esta locução deve ser separada por vírgulas.
Context: ... Ativar masking de tool results no open build quando autonomy está ON. **Mecanismo (...
(VERB_COMMA_CONJUNCTION)
docs/superpowers/knowledge/README.md
[locale-violation] ~26-~26: “Template” é um estrangeirismo. É preferível dizer “modelo”.
Context: ...E.md](./SESSION_INSIGHTS_TEMPLATE.md) | Template de insight de sessão | Pronto | | [2026...
(PT_BARBARISMS_REPLACE_TEMPLATE)
[locale-violation] ~30-~30: “budget” é um estrangeirismo. É preferível dizer “orçamento” ou “verba”.
Context: ...to | | 2026-07-09-ollama-first-fleet.md | Frota Ollama | Feito | | [...
(PT_BARBARISMS_REPLACE_BUDGET)
[locale-violation] ~30-~30: “budget” é um estrangeirismo. É preferível dizer “orçamento” ou “verba”.
Context: ...-09-ollama-first-fleet.md) | Frota Ollama | Feito | | [2026-07-09-phase5-context-budge...
(PT_BARBARISMS_REPLACE_BUDGET)
[uncategorized] ~55-~55: Se é uma abreviatura, falta um ponto. Se for uma expressão, coloque entre aspas.
Context: ... É regra de ouro do repositório (build, test, paths Windows) Não promova: prefe...
(ABREVIATIONS_PUNCTUATION)
docs/superpowers/knowledge/2026-07-09-phase1-shipped.md
[locale-violation] ~3-~3: “performance” é um estrangeirismo. É preferível dizer “desempenho”, “atuação”, “apresentação”, “espetáculo” ou “interpretação”.
Context: ...Implementação da Phase 1 do programa de performance/autonomia no OpenClaude. Sintoma: ...
(PT_BARBARISMS_REPLACE_PERFORMANCE)
[uncategorized] ~15-~15: Se é uma abreviatura, falta um ponto. Se for uma expressão, coloque entre aspas.
Context: ...ultado:** 36 testes unitários passando (bun run test:autonomy). **Política sugerida (aplic...
(ABREVIATIONS_PUNCTUATION)
docs/superpowers/knowledge/ROUTING_BASELINE.md
[inconsistency] ~10-~10: O URL contém o caratére inválido segundo RFC 1738. Os caratéres especiais podem ser codificados com % seguido de dois números hexadecimais. Context: ...rofile |openai| | OPENAI_BASE_URL |https://token-plan-sgp.xiaomimimo.com/v1` | | OPENAI_MODEL | mimo-v2.5-pro | >...
(URL_VALIDATION)
[style] ~11-~11: Em contextos mais formais, prefira “para”.
Context: ...p.xiaomimimo.com/v1| | OPENAI_MODEL |mimo-v2.5-pro` | > Nota: o profile de trabalho atual...
(FORMAL_PRA_PARA)
docs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.md
[grammar] ~71-~71: Ensure spelling is correct
Context: ...el) - Provider health + latency scores (port of SmartRouter ideas) - Policy → model/...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
docs/superpowers/specs/2026-07-09-phase6-hybrid-local-intelligence.md
[grammar] ~62-~62: Use a hyphen to join words.
Context: ...Success metrics:* - Wall-clock on mid coding tasks ↓ 20–40% vs always-hard - P...
(QB_NEW_EN_HYPHEN)
GUIA_USO.md
[uncategorized] ~3-~3: Verifique se não quis dizer “é”, ou talvez insira uma vírgula.
Context: ...penClaude Agent - Guia de Uso ## O que e o OpenClaude O OpenClaude e um **agent...
(CONFUSÃO_E_É)
[grammar] ~14-~14: Possível fragmento.
Context: ... autonomos ate completar a tarefa Voce da o objetivo, ele decide quais ferramentas ...
(FRAGMENT_TWO_ARTICLES)
[uncategorized] ~36-~36: Se pretende usar a preposição ‘até’, acrescente o acento agudo.
Context: ...pido ### 1. Abrir PowerShell e navegar ate o agente ```powershell cd E:\Agente_Op...
(CONFUSÃO_ATE_ATÉ)
[uncategorized] ~88-~88: Se é uma abreviatura, falta um ponto. Se for uma expressão, coloque entre aspas.
Context: ..., Claude, GPT, Gemini, Llama, DeepSeek, etc). Ideal para usar modelos gratuitos pre...
(ABREVIATIONS_PUNCTUATION)
[uncategorized] ~103-~103: Quando escrita sem acento, esta palavra é um verbo. Se pretende referir-se a um substantivo ou adjetivo, deve utilizar a forma acentuada.
Context: ...ns:** Modelos premium pagos precisam de creditos na conta OpenRouter **Como selecionar ...
(LP_PARONYMS)
[misspelling] ~116-~116: Possível erro ortográfico.
Context: ... | | Claude Sonnet 4.5 | anthropic/claude-sonnet-4.5 | $3.00 ...
(PT_MULTITOKEN_SPELLING_HYPHEN)
[style] ~119-~119: Em contextos mais formais, prefira “para”.
Context: ... | | Gemini 2.5 Pro | google/gemini-2.5-pro | $1.25 ...
(FORMAL_PRA_PARA)
[uncategorized] ~128-~128: Se pretende usar a preposição ‘até’, acrescente o acento agudo.
Context: ...delos locais na GPU (RTX 4090). Modelos ate 14B cabem na VRAM. ```powershell .\sta...
(CONFUSÃO_ATE_ATÉ)
[uncategorized] ~144-~144: Quando escrita sem acento, esta palavra é um verbo. Se pretende referir-se a um substantivo ou adjetivo, deve utilizar a forma acentuada.
Context: ...s de Uso por Projeto ### Relatorios de Pericias ```powershell .\start-ollama.ps1 -Proj...
(LP_PARONYMS)
[locale-violation] ~375-~375: “budget” é um estrangeirismo. É preferível dizer “orçamento” ou “verba”.
Context: ...er a rota ativa. ### Phase 5 — Context budget (mask de tool results) Com autonomy ON...
(PT_BARBARISMS_REPLACE_BUDGET)
[uncategorized] ~377-~377: Deve-se utilizar a vírgula antes de ‘etc.’.
Context: ... resultados grandes de tools (Bash/Grep/etc.) sao persistidos em disco e o mode...
(ETC_USAGE)
[locale-violation] ~381-~381: “budget” é um estrangeirismo. É preferível dizer “orçamento” ou “verba”.
Context: ...--| | maskToolResults | true | Liga o budget de tool results | | `maxToolResultChars...
(PT_BARBARISMS_REPLACE_BUDGET)
[misspelling] ~439-~439: Possível erro de acentuação. Verifique se não quis dizer “após”.
Context: ... sessao: ~/.openclaude/insights/*.md (apos turnos com autonomy) - Comando **`/rout...
(DIACRITICS)
[style] ~489-~489: Em textos formais, legais ou jurídicos, prefira “moroso”.
Context: ...i # openai ### Resposta muito lenta Verifique se esta usando GPU: powe...
(LENTO_MOROSO)
[uncategorized] ~501-~501: Substitua por “está”.
Context: ...onexao com OpenAI Verifique se a chave esta configurada: ```powershell echo $env:O...
(ESTA_ESTÁ)
[uncategorized] ~520-~520: Esta locução deve ser separada por vírgulas.
Context: ...e na 4090) | | 200B+ (cloud/API) | Sim | Para uso como ...
(VERB_COMMA_CONJUNCTION)
🪛 markdownlint-cli2 (0.22.1)
docs/superpowers/plans/2026-07-09-agent-performance-autonomy.md
[warning] 31-31: Table column count
Expected: 2; Actual: 5; Too many cells, extra data will be missing
(MD056, table-column-count)
[warning] 216-216: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 299-299: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 469-469: Spaces inside emphasis markers
(MD037, no-space-in-emphasis)
[warning] 469-469: Spaces inside emphasis markers
(MD037, no-space-in-emphasis)
docs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.md
[warning] 84-84: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 271-271: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 274-274: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 277-277: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 280-280: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 283-283: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 286-286: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 289-289: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
docs/superpowers/specs/2026-07-09-phase6-hybrid-local-intelligence.md
[warning] 169-169: Ordered list item prefix
Expected: 1; Actual: 4; Style: 1/2/3
(MD029, ol-prefix)
[warning] 170-170: Ordered list item prefix
Expected: 2; Actual: 5; Style: 1/2/3
(MD029, ol-prefix)
[warning] 171-171: Ordered list item prefix
Expected: 3; Actual: 6; Style: 1/2/3
(MD029, ol-prefix)
GUIA_USO.md
[warning] 181-181: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 185-185: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 191-191: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 195-195: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 201-201: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 205-205: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 211-211: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
[warning] 217-217: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🪛 PSScriptAnalyzer (1.25.0)
start-ollama.ps1
[warning] Missing BOM encoding for non-ASCII encoded file 'start-ollama.ps1'
(PSUseBOMForUnicodeEncodedFile)
🔇 Additional comments (46)
src/services/autonomy/complexityClassifier.test.ts (1)
1-53: LGTM!src/services/autonomy/index.ts (1)
1-76: LGTM!src/services/autonomy/complexityClassifier.ts (1)
1-62: LGTM!src/services/api/agentRouting.ts (1)
2-8: LGTM!Also applies to: 21-30, 32-38, 48-95, 96-175
src/services/autonomy/telemetry.ts (1)
33-44: 📐 Maintainability & Code QualitySame lazy
require()pattern asresolveForMessages.ts.Per coding guidelines, TypeScript in this repo should use ESM imports; these are CJS
require()calls (with eslint-disable). Same tradeoff/justification as the sibling file — noting here for consistency, not raising separately.Also applies to: 47-55
Source: Coding guidelines
docs/superpowers/knowledge/2026-07-09-consistency-eval.md (1)
1-59: LGTM!src/services/autonomy/resolveForMessages.test.ts (1)
1-53: LGTM!docs/superpowers/knowledge/2026-07-09-phase5-context-budget.md (1)
1-13: LGTM!src/commands.ts (1)
190-190: LGTM!Also applies to: 282-282
src/services/autonomy/telemetry.test.ts (1)
1-48: LGTM!docs/superpowers/knowledge/2026-07-09-ollama-first-fleet.md (1)
1-35: LGTM!src/services/autonomy/routePolicy.test.ts (1)
1-181: LGTM!package.json (1)
33-38: LGTM! The new autonomy scripts look good.docs/superpowers/knowledge/ROUTING_BASELINE.md (1)
1-89: LGTM!src/commands/route/route.ts (1)
19-89: LGTM!src/utils/settings/types.ts (1)
737-820: LGTM! The new schema fields are well-structured, all optional, and backward compatible.scripts/apply-ollama-autonomy.ts (1)
41-83: LGTM! The autonomy policy configuration and backup logic look solid.src/services/autonomy/circuitBreakers.test.ts (1)
1-62: LGTM!src/services/autonomy/providerFallback.test.ts (1)
1-134: LGTM!src/tools/AgentTool/runAgent.ts (1)
352-367: LGTM!src/commands/route/index.ts (1)
1-12: LGTM!src/services/autonomy/contextBudget.test.ts (1)
1-80: LGTM!src/utils/toolResultStorage.ts (1)
77-90: LGTM!Also applies to: 447-458, 477-492
start-ollama.ps1 (2)
16-173: LGTM!
86-93: 🔒 Security & PrivacyNo action needed on
.env.openrouter..gitignorealready ignores.envand.env.*, so the file stays untracked.> Likely an incorrect or invalid review comment.src/services/autonomy/contextBudget.ts (1)
1-125: LGTM!scripts/doctor-autonomy.ts (1)
1-67: LGTM!Also applies to: 73-162
src/query/stopHooks.ts (1)
157-174: LGTM!docs/superpowers/knowledge/README.md (1)
1-82: LGTM!docs/superpowers/knowledge/2026-07-09-phase2-health-fallback.md (1)
1-24: LGTM!docs/superpowers/knowledge/2026-07-09-phase1-shipped.md (1)
1-40: LGTM!src/services/autonomy/sessionInsights.ts (2)
39-59: LGTM!Also applies to: 61-123, 125-183
16-37: 📐 Maintainability & Code QualityConfirm the runtime for these lazy imports. If this file can execute under Node ESM, bare
require()will hit thecatchpath and silently disable insights/session IDs unless Bun rewrites it in the production bundle. Useimport()orcreateRequireif that path is real.docs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.md (1)
1-362: LGTM!src/services/autonomy/routePolicy.ts (1)
1-49: LGTM!Also applies to: 57-254
src/services/autonomy/providerHealth.test.ts (1)
1-71: LGTM!src/services/api/withRetry.ts (1)
151-158: LGTM!Also applies to: 206-206, 253-260, 274-298
src/services/autonomy/consistency.integration.test.ts (2)
70-207: LGTM on the remaining test coverage — tests are well-structured with proper isolation viabeforeEachresets.
118-133: 🎯 Functional CorrectnessDrop this warning about an empty trivial fallback chain.
resolveTaskRouteusesfallbackChains.defaultwhenfallbackChains.trivialis missing, soqwen2.5:7bcan still be replaced here. The inline note about “may stay” is misleading.> Likely an incorrect or invalid review comment.src/services/autonomy/providerHealth.ts (1)
1-275: LGTM!src/query.ts (1)
700-704: LGTM!src/Tool.ts (1)
179-191: LGTM!src/services/tools/toolOrchestration.ts (1)
31-84: LGTM!Also applies to: 106-149
src/services/tools/StreamingToolExecutor.ts (1)
56-60: LGTM!Also applies to: 86-89, 154-177, 403-422, 497-509
src/services/autonomy/circuitBreakers.ts (1)
39-45: 🎯 Functional Correctness
FileEdit/FileWritedon’t affect this bridge path.extractToolObservation()only seesEdit/Write/NotebookEdit, and the file-edit/write tool names are still exported asEditandWrite. The extraEDIT_TOOLSentries appear unused here, so this mismatch does not break noop streak handling.> Likely an incorrect or invalid review comment.src/services/autonomy/circuitToolBridge.ts (1)
16-32: 📐 Maintainability & Code QualityNo blocker here This file follows the repo’s existing lazy
require()pattern inside ESM TypeScript modules and the bundled CLI path, so this isn’t a runtime regression.> Likely an incorrect or invalid review comment.
| ## What to test | ||
|
|
||
| ```powershell | ||
| cd E:\Agente_OpenClaude |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Replace hardcoded Windows path with a relative/generic reference.
E:\Agente_OpenClaude is a machine-specific absolute path. Other contributors on macOS/Linux cannot use it. Replace with a generic instruction like cd <your-openclaude-repo>.
🤖 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 `@docs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.md` at line 8, The setup
instruction currently uses a machine-specific absolute Windows path, which
breaks portability. Update the command in the STOP-AND-TEST guidance to use a
generic relative or placeholder repo path instead of E:\Agente_OpenClaude, and
keep the wording reusable for contributors on any OS. Refer to the path example
in the markdown and replace it with a neutral instruction like changing into the
OpenClaude repository directory.
Source: Path instructions
| | Requisito | Versao Minima | Verificar | | ||
| | --------- | ------------- | ------------------ | | ||
| | Node.js | 20+ | `node --version` | | ||
| | Ollama | qualquer | `ollama --version` | | ||
| | Bun (dev) | 1.3.11+ | `bun --version` | |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Node.js minimum version is incorrect.
The guide states Node.js 20+ but AGENTS.md specifies >=22.0.0. This could mislead users into using an unsupported runtime.
📝 Proposed fix
| Requisito | Versao Minima | Verificar |
| --------- | ------------- | ------------------ |
-| Node.js | 20+ | `node --version` |
+| Node.js | 22+ | `node --version` |
| Ollama | qualquer | `ollama --version` |
| Bun (dev) | 1.3.11+ | `bun --version` |As per coding guidelines, the installed CLI runs on Node.js >=22.0.0.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| | Requisito | Versao Minima | Verificar | | |
| | --------- | ------------- | ------------------ | | |
| | Node.js | 20+ | `node --version` | | |
| | Ollama | qualquer | `ollama --version` | | |
| | Bun (dev) | 1.3.11+ | `bun --version` | | |
| | Requisito | Versao Minima | Verificar | | |
| | --------- | ------------- | ------------------ | | |
| | Node.js | 22+ | `node --version` | | |
| | Ollama | qualquer | `ollama --version` | | |
| | Bun (dev) | 1.3.11+ | `bun --version` | |
🤖 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 `@GUIA_USO.md` around lines 20 - 24, Update the runtime requirements table in
GUIA_USO.md so the Node.js minimum version matches AGENTS.md and the installed
CLI requirement; change the Node.js entry from 20+ to >=22.0.0. Keep the rest of
the table unchanged and verify the “Verificar” command still reflects the
intended version check.
Source: Coding guidelines
|
|
||
| ollama run kimi-k2.6:nuvem | ||
|
|
||
| ## Trocar Modelo na Hora | ||
|
|
||
| ```powershell | ||
| # Cloud (235B - agente completo) | ||
| ESTA | ||
|
|
||
| # Cloud alternativo (355B) | ||
| .\start-ollama.ps1 -Model "glm-4.6:cloud" | ||
|
|
||
| # OpenAI GPT-4o | ||
| .\start-ollama.ps1 -Mode openai -Model "gpt-4o" | ||
|
|
||
| # OpenAI GPT-4o mini (mais barato) | ||
| .\start-ollama.ps1 -Mode openai -Model "gpt-4o-mini" | ||
| ``` | ||
|
|
||
| ## .\start-ollama.ps1 -Model "kimi-k2.6:cloud" |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Stray content and editing artifacts in the "Trocar Modelo" section.
- Line 271:
ollama run kimi-k2.6:nuvemis outside a code block — appears to be a stray command. - Line 277:
ESTAinside a code block — appears to be placeholder or incomplete text. - Line 289:
## .\start-ollama.ps1 -Model "kimi-k2.6:cloud"is a heading containing a command — confusing structure.
These look like editing artifacts that should be cleaned up before merge.
🤖 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 `@GUIA_USO.md` around lines 270 - 289, The “Trocar Modelo na Hora” section in
GUIA_USO.md contains stray editing artifacts that should be cleaned up. Remove
the standalone `ollama run kimi-k2.6:nuvem` command if it is not meant to be
part of the section, replace the placeholder `ESTA` with the intended content or
delete it from the fenced block, and change the heading that embeds
`.\start-ollama.ps1 -Model "kimi-k2.6:cloud"` into a proper descriptive heading
with the command moved into its own code block.
| "scripts": { | ||
| "build": "bun run scripts/build.ts", | ||
| "dev": "bun run build && node dist/cli.mjs", | ||
| "dev": "bun run build && bun dist/cli.mjs", |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | 🏗️ Heavy lift
Revert dev, start, and smoke scripts from bun back to node runtime.
AGENTS.md states: "The installed CLI runs on Node.js >=22.0.0" and "Do not change the Node runtime or Bun development workflow without prior maintainer agreement." Switching dev, start, and smoke to bun dist/cli.mjs changes the CLI runtime from Node to Bun without documented maintainer approval. The smoke test in particular must run under Node to catch Node-specific runtime issues in the built CLI.
As per coding guidelines: "Do not change the Node runtime or Bun development workflow without prior maintainer agreement."
🔧 Proposed fix
- "dev": "bun run build && bun dist/cli.mjs",
+ "dev": "bun run build && node dist/cli.mjs",- "start": "bun dist/cli.mjs",
+ "start": "node dist/cli.mjs",- "smoke": "bun run build && bun dist/cli.mjs --version",
+ "smoke": "bun run build && node dist/cli.mjs --version",Also applies to: 39-39, 42-42
🤖 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 `@package.json` at line 16, Revert the package.json scripts for dev, start, and
smoke back to running the CLI under Node instead of bun, since the current
changes in the dev/start/smoke entries switch the runtime away from the
supported Node.js workflow. Update those script definitions in package.json to
use the Node-based CLI invocation already used by the project, and keep the
existing build step intact so the scripts continue to exercise the built CLI
under Node.
Sources: Coding guidelines, Path instructions
| const raw = readFileSync(settingsPath, 'utf8') | ||
| const settings = JSON.parse(raw) as Record<string, unknown> |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Wrap JSON.parse in try/catch with a clear error message.
If ~/.claude/settings.json is corrupted or empty, JSON.parse throws an unhelpful stack trace. Catch and print a actionable message.
🛡️ Proposed fix
const raw = readFileSync(settingsPath, 'utf8')
- const settings = JSON.parse(raw) as Record<string, unknown>
+ let settings: Record<string, unknown>
+ try {
+ settings = JSON.parse(raw) as Record<string, unknown>
+ } catch {
+ console.error(`Invalid JSON in ${settingsPath}. Fix or remove it before re-running.`)
+ process.exit(1)
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const raw = readFileSync(settingsPath, 'utf8') | |
| const settings = JSON.parse(raw) as Record<string, unknown> | |
| const raw = readFileSync(settingsPath, 'utf8') | |
| let settings: Record<string, unknown> | |
| try { | |
| settings = JSON.parse(raw) as Record<string, unknown> | |
| } catch { | |
| console.error(`Invalid JSON in ${settingsPath}. Fix or remove it before re-running.`) | |
| process.exit(1) | |
| } |
🤖 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 `@scripts/apply-ollama-autonomy.ts` around lines 33 - 34, Wrap the JSON.parse
call in the settings-loading flow so corrupted or empty settings files produce a
clear actionable message instead of an uncaught stack trace. In the code that
reads settingsPath and parses raw into settings, add a try/catch around
JSON.parse, and on failure surface a descriptive error that mentions the
settings file could not be parsed and suggests checking ~/.claude/settings.json
for corruption or emptiness. Keep the behavior localized to the settings parsing
logic in apply-ollama-autonomy.ts.
| const userText = extractUserTextFromMessages(input.messages) | ||
| // Prefer last user turn only for classification (avoid cumulative context noise) | ||
| const lastUserOnly = userText.split('\n').slice(-8).join('\n') | ||
| const hasImage = messagesHaveImage(input.messages) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
"Last user turn only" comment doesn't match implementation.
extractUserTextFromMessages joins all user turns with \n, then lastUserOnly blindly takes the last 8 lines of that joined string — not the last user turn. Multi-line user messages or multiple short turns will mix content across turns, undermining the stated intent to avoid "cumulative context noise" for classification.
🐛 Proposed fix
+export function extractLastUserTurnText(messages: Message[]): string {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const message = messages[i]
+ if (message.type !== 'user') continue
+ const content = message.message.content
+ if (typeof content === 'string') return content
+ if (Array.isArray(content)) {
+ return content.filter(b => b.type === 'text' && 'text' in b).map(b => b.text).join('\n')
+ }
+ }
+ return ''
+}
+
const userText = extractUserTextFromMessages(input.messages)
-const lastUserOnly = userText.split('\n').slice(-8).join('\n')
+const lastUserOnly = extractLastUserTurnText(input.messages)🤖 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 `@src/services/autonomy/resolveForMessages.ts` around lines 64 - 67, The
current “last user turn only” logic in resolveForMessages is using
extractUserTextFromMessages plus a line-based slice, which can mix multiple
turns and multi-line content. Update the classification input so it selects the
actual last user message/turn from input.messages rather than truncating the
joined user text, and keep the hasImage check unchanged. Use the existing
resolveForMessages and extractUserTextFromMessages flow as the entry point, but
make the turn selection explicit and turn-based so the comment matches the
implementation.
| export function isAutonomyEnabled( | ||
| settings: SettingsJson | null | undefined, | ||
| ): boolean { | ||
| if (isEnvTruthy(process.env.OPENCLAUDE_AUTONOMY)) return true | ||
| if (process.env.OPENCLAUDE_AUTONOMY === '0') return false | ||
| return Boolean(settings?.autonomy?.enabled) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
isAutonomyEnabled doesn't handle OPENCLAUDE_AUTONOMY=false — inconsistent with doctor-autonomy.ts.
envAutonomyEnabled in doctor-autonomy.ts (lines 50-55) explicitly checks both '0' and 'false' to disable autonomy. This function only checks '0'. If a user sets OPENCLAUDE_AUTONOMY=false:
isEnvTruthy('false')→ false (doesn't return true)process.env.OPENCLAUDE_AUTONOMY === '0'→ false (doesn't match)- Falls through to
Boolean(settings?.autonomy?.enabled)→ may return true
The doctor report would show autonomy as disabled while the actual routing path keeps it enabled. This silent inconsistency could lead to unexpected model routing when the user believes they've turned autonomy off.
🐛 Proposed fix
export function isAutonomyEnabled(
settings: SettingsJson | null | undefined,
): boolean {
if (isEnvTruthy(process.env.OPENCLAUDE_AUTONOMY)) return true
- if (process.env.OPENCLAUDE_AUTONOMY === '0') return false
+ if (process.env.OPENCLAUDE_AUTONOMY === '0' || process.env.OPENCLAUDE_AUTONOMY === 'false') return false
return Boolean(settings?.autonomy?.enabled)
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function isAutonomyEnabled( | |
| settings: SettingsJson | null | undefined, | |
| ): boolean { | |
| if (isEnvTruthy(process.env.OPENCLAUDE_AUTONOMY)) return true | |
| if (process.env.OPENCLAUDE_AUTONOMY === '0') return false | |
| return Boolean(settings?.autonomy?.enabled) | |
| } | |
| export function isAutonomyEnabled( | |
| settings: SettingsJson | null | undefined, | |
| ): boolean { | |
| if (isEnvTruthy(process.env.OPENCLAUDE_AUTONOMY)) return true | |
| if (process.env.OPENCLAUDE_AUTONOMY === '0' || process.env.OPENCLAUDE_AUTONOMY === 'false') return false | |
| return Boolean(settings?.autonomy?.enabled) | |
| } |
🤖 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 `@src/services/autonomy/routePolicy.ts` around lines 50 - 56,
`isAutonomyEnabled` treats OPENCLAUDE_AUTONOMY as disabled only for "0", which
is inconsistent with the autonomy check used elsewhere. Update the environment
handling in `isAutonomyEnabled` to also return false when OPENCLAUDE_AUTONOMY is
set to "false", keeping it aligned with the logic in `doctor-autonomy.ts` and
preventing fallback to settings when the env var explicitly disables autonomy.
| const VISION_RE = | ||
| /\b(screenshot|imagem|image|print|foto|photo|ui mock|wireframe|diagrama visual)\b/i |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
print in VISION_RE causes false positives in a coding agent context.
In a coding CLI, "print" is extremely common ("print the output", "add a print statement", "print the array"). Since classifyComplexity checks vision first, any prompt containing "print" is classified as vision tier — overriding path mentions, architecture keywords, and all other signals. When taskRouting.vision is configured (as the PR encourages), these standard coding prompts get routed to a vision model unnecessarily.
Remove print or narrow it to print ?screen|printscreen to avoid matching the programming term.
🐛 Proposed fix for VISION_RE false positive
const VISION_RE =
- /\b(screenshot|imagem|image|print|foto|photo|ui mock|wireframe|diagrama visual)\b/i
+ /\b(screenshot|imagem|image|foto|photo|ui mock|wireframe|diagrama visual|print ?screen|printscreen)\b/i📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const VISION_RE = | |
| /\b(screenshot|imagem|image|print|foto|photo|ui mock|wireframe|diagrama visual)\b/i | |
| const VISION_RE = | |
| /\b(screenshot|imagem|image|foto|photo|ui mock|wireframe|diagrama visual|print ?screen|printscreen)\b/i |
🤖 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 `@src/services/autonomy/taskSignals.ts` around lines 33 - 34, The VISION_RE
pattern in taskSignals.ts is too broad because it matches the common coding term
“print,” which causes classifyComplexity to route ordinary CLI prompts to vision
first. Update VISION_RE to remove the standalone print token or narrow it to a
screenshot-specific phrase such as printscreen/print screen, while keeping the
existing vision-related terms intact so taskRouting.vision only triggers on
actual visual requests.
| export async function readRecentTelemetry( | ||
| limit = 20, | ||
| ): Promise<TurnTelemetryEvent[]> { | ||
| try { | ||
| const { readFile } = await import('fs/promises') | ||
| const raw = await readFile(getTelemetryPath(), 'utf8') | ||
| const lines = raw.trim().split('\n').filter(Boolean) | ||
| const slice = lines.slice(-limit) | ||
| const out: TurnTelemetryEvent[] = [] | ||
| for (const line of slice) { | ||
| try { | ||
| out.push(JSON.parse(line) as TurnTelemetryEvent) | ||
| } catch { | ||
| // skip bad lines | ||
| } | ||
| } | ||
| return out | ||
| } catch { | ||
| return [] | ||
| } | ||
| } |
There was a problem hiding this comment.
🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win
Unbounded telemetry file growth + inline dynamic import.
readRecentTelemetry reads the whole turns.jsonl into memory on every call — since this file is appended to on every route selection over a long-lived session, it grows without bound and this read cost grows with it (used by /route and doctor:autonomy, likely called repeatedly). Consider capping file size / rotating on write (e.g. truncate to last N lines once above a size threshold) instead of relying on callers to pass a small limit.
Minor nit: line 93 does await import('fs/promises') for readFile even though appendFile/mkdir are already statically imported from the same module at the top of the file — could just add readFile to the existing import.
🤖 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 `@src/services/autonomy/telemetry.ts` around lines 89 - 109,
`readRecentTelemetry` currently loads the entire `turns.jsonl` file into memory
on every call, so the telemetry log can grow without bound and make `/route` and
`doctor:autonomy` progressively slower. Update the telemetry write/read flow in
`readRecentTelemetry` and the related append path in this module to enforce a
bounded history, such as truncating/rotating to the last N lines when the file
exceeds a size threshold, instead of relying on callers’ `limit`. Also remove
the inline `await import('fs/promises')` in `readRecentTelemetry` by using the
existing static imports from that module and adding `readFile` alongside them.
| # ============================================================ | ||
| # OpenClaude Agent - Script de Lancamento (PowerShell) | ||
| # ============================================================ | ||
| # Uso: | ||
| # .\start-ollama.ps1 → cloud (qwen3-vl:235b) | ||
| # .\start-ollama.ps1 -Mode local → local 14B na GPU | ||
| # .\start-ollama.ps1 -Mode openai → GPT-4o (plano B) | ||
| # .\start-ollama.ps1 -Mode openrouter → OpenRouter (Claude, GPT, etc) | ||
| # .\start-ollama.ps1 -AutonomyMode smart → routing por complexidade | ||
| # .\start-ollama.ps1 -AutonomyMode fast → prefere modelos pequenos | ||
| # .\start-ollama.ps1 -AutonomyMode quality → prefere modelos grandes | ||
| # .\start-ollama.ps1 -AutonomyMode fixed → desliga task routing | ||
| # .\start-ollama.ps1 -Project "E:\meu-projeto" → abrir em diretorio | ||
| # .\start-ollama.ps1 -Mode local -Project "E:\proj" → combinar opcoes | ||
| # ============================================================ |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add UTF-8 BOM to the file.
The file contains non-ASCII characters (→ arrows in usage comments) but lacks a BOM. PowerShell on systems with non-UTF-8 default encoding may garble these characters. PSScriptAnalyzer flags this as PSUseBOMForUnicodeEncodedFile.
Save the file as UTF-8 with BOM encoding.
🧰 Tools
🪛 PSScriptAnalyzer (1.25.0)
[warning] Missing BOM encoding for non-ASCII encoded file 'start-ollama.ps1'
(PSUseBOMForUnicodeEncodedFile)
🤖 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 `@start-ollama.ps1` around lines 1 - 15, The PowerShell launch script contains
non-ASCII usage text but is saved without a UTF-8 BOM, so update
start-ollama.ps1 to be encoded as UTF-8 with BOM. Preserve the existing comment
content and ensure the file is re-saved with BOM so PowerShell reads the arrows
and other Unicode characters correctly, addressing the
PSUseBOMForUnicodeEncodedFile warning.
Source: Linters/SAST tools
|
Thank you for the time and effort that clearly went into this contribution. There are several promising ideas here, and I appreciate the attempt to improve autonomy, routing, safety, and local-model workflows. That said, I do not think this PR is reviewable or safe to merge in its current shape. It combines a very large amount of unrelated work: runtime routing and retry behavior, tool-loop safety, telemetry and persistence, launch scripts, user settings mutation, package-runtime changes, a new command, and a substantial documentation/design bundle. The breadth also makes it difficult to establish a clear contract, test the behavioral changes independently, or safely reason about regressions. Most importantly, the setup path writes directly to user configuration, targets the wrong configuration directory, and currently replaces existing provider and routing settings. Changes that can alter or discard a user's local configuration need a much narrower scope, explicit safety guarantees, and focused tests before they can be considered. The documentation additions are also far broader than needed to support a single implementation change, and include design material, future-phase planning, and unrelated guide content. Please keep implementation PRs focused on the behavior they introduce, with only the documentation required to use and maintain that behavior. Could you please break this work into several small, independently standing PRs? For example:
Each PR should rebase on current I am going to close this PR for now rather than try to untangle the combined change set here. You are very welcome to open smaller, independently reviewable follow-up PRs for the pieces you would still like to pursue. |
Summary
Adds an Autonomy Controller layer on top of OpenClaude so agent turns route by task complexity, prefer the local Ollama fleet when appropriate, fail over on provider health errors, and stop runaway tool loops — without rewriting QueryEngine.
trivial/standard/hard/vision) via heuristic classifier +taskRoutingsettingssmart|fast|code|quality|fixed(env +start-ollama.ps1)withRetry)runToolsandStreamingToolExecutorresolveForMessages)/routecommand,doctor:autonomybun run autonomy:ollamaTest plan
bun test src/services/autonomy src/services/api/agentRouting.test.ts(72 pass)bun run build→dist/cli.mjs0.1.7bun run doctor:autonomy/:probewith Ollama fleet healthy.\start-ollama.ps1→/route→ trivial / standard / hard promptsagentRoutingonlyDocs
docs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.mddocs/superpowers/plans/2026-07-09-agent-performance-autonomy.mddocs/superpowers/knowledge/*GUIA_USO.md(Ollama-first)Notes for maintainers
autonomy,taskRouting,fallbackChains(backward compatible when disabled)bun run autonomy:ollama(not committed secrets)Summary by CodeRabbit
New Features
/routecommand for viewing autonomy routing, health, and recent decisions.Documentation