Skip to content

feat(autonomy): task-tier routing, Ollama fleet, health/fallback, and safety - #1921

Closed
alanoliveira2025 wants to merge 10 commits into
Twigpine:mainfrom
alanoliveira2025:feature/autonomy-phase1
Closed

alanoliveira2025 wants to merge 10 commits into
Twigpine:mainfrom
alanoliveira2025:feature/autonomy-phase1

Conversation

@alanoliveira2025

@alanoliveira2025 alanoliveira2025 commented Jul 9, 2026 •

Copy link
Copy Markdown

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.

  • Task-tier routing (trivial / standard / hard / vision) via heuristic classifier + taskRouting settings
  • Modes: smart | fast | code | quality | fixed (env + start-ollama.ps1)
  • Provider health + fallback chains (EMA latency, unhealthy after consecutive failures, live failover in withRetry)
  • Circuit breakers on serial runTools and StreamingToolExecutor
  • Main-thread + subagent share the same resolve path (resolveForMessages)
  • Per-route effort for API calls without thrashing AppState/UI
  • Local knowledge loop: turn telemetry JSONL, session insights, /route command, doctor:autonomy
  • Ollama-first policy helper: bun run autonomy:ollama

Test plan

  • bun test src/services/autonomy src/services/api/agentRouting.test.ts (72 pass)
  • bun run build → dist/cli.mjs 0.1.7
  • bun run doctor:autonomy / :probe with Ollama fleet healthy
  • Interactive smoke: .\start-ollama.ps1 → /route → trivial / standard / hard prompts
  • Confirm fallback when a cloud model is unavailable
  • Confirm autonomy off path still uses legacy agentRouting only

Docs

  • docs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.md
  • docs/superpowers/plans/2026-07-09-agent-performance-autonomy.md
  • docs/superpowers/knowledge/*
  • GUIA_USO.md (Ollama-first)

Notes for maintainers

  • Settings schema extended: autonomy, taskRouting, fallbackChains (backward compatible when disabled)
  • User-local settings are applied via bun run autonomy:ollama (not committed secrets)
  • Phases 5–6 (context masking / draft-model / RAG) intentionally deferred until post-merge validation

Summary by CodeRabbit

  • New Features

    • Added autonomy-aware task-tier routing (including image-aware classification), health-based provider selection, and fallback/failover behavior.
    • Introduced circuit-breakers to stop repeated tool failures/no-op edit loops during autonomous runs.
    • Added automatic session insights generation and new /route command for viewing autonomy routing, health, and recent decisions.
    • Added/updated launch and setup support for autonomy modes (via the Ollama starter) and improved provider failover during streaming.
  • Documentation

    • Added a full Portuguese user guide plus multiple new autonomy/knowledge-base pages (routing baselines, phased autonomy progress, health/fallback, context budget/masking, fleet setup, and evaluation/quality notes).

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.
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Autonomy Feature Implementation

Layer / File(s) Summary
Settings, task signals, and route policy
src/utils/settings/types.ts, src/Tool.ts, src/services/autonomy/taskSignals.ts, src/services/autonomy/complexityClassifier.ts, src/services/autonomy/routePolicy.ts, src/services/api/agentRouting.ts, src/services/autonomy/*test.ts
Adds autonomy settings and provider override metadata, derives task tiers from prompts, and resolves routing decisions with legacy fallback and mode biasing.
Provider health and fallback
src/services/autonomy/providerHealth.ts, src/services/autonomy/providerFallback.ts, src/services/autonomy/*test.ts
Tracks provider health and latency, probes endpoints, and selects or advances fallback providers on health or API failures.
Runtime routing and retry wiring
src/services/api/claude.ts, src/services/api/withRetry.ts, src/services/autonomy/resolveForMessages.ts, src/screens/REPL.tsx, src/tools/AgentTool/runAgent.ts, src/query.ts
Feeds autonomy overrides into request execution, retry failover, REPL/main-loop routing, and agent spawning, and applies override effort when calling models.
Circuit breakers and tool orchestration
src/services/autonomy/circuitBreakers.ts, src/services/autonomy/circuitToolBridge.ts, src/services/tools/StreamingToolExecutor.ts, src/services/tools/toolOrchestration.ts, src/services/autonomy/*test.ts
Detects repeated tool failures/no-op edits, trips tool loops, cancels queued work, and emits circuit-trip messages.
Telemetry, insights, and context budget
src/services/autonomy/telemetry.ts, src/services/autonomy/sessionInsights.ts, src/services/autonomy/contextBudget.ts, src/query/stopHooks.ts, src/utils/toolResultStorage.ts, src/services/autonomy/*test.ts
Writes local telemetry, generates session-insight markdown, and gates tool-result masking and persistence budgets from autonomy settings.
Commands, scripts, and launch wiring
src/services/autonomy/index.ts, src/commands/route/*, src/commands.ts, scripts/doctor-autonomy.ts, scripts/apply-ollama-autonomy.ts, package.json, start-ollama.ps1
Adds the /route command, autonomy doctor and setup scripts, npm/Bun script updates, and the launch flag for autonomy mode.
Guides, plans, and knowledge base
GUIA_USO.md, docs/superpowers/knowledge/*, docs/superpowers/plans/*, docs/superpowers/specs/*
Adds the user guide and the project knowledge, planning, and design documents for the rollout.
Autonomy integration tests
src/services/autonomy/consistency.integration.test.ts
Validates routing, health failover, circuit breakers, classifier determinism, and autonomy mode behavior end to end.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested labels: enhancement

🚥 Pre-merge checks | ✅ 5 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.97% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
No Hidden Policy Change ⚠️ Warning start-ollama.ps1 now enables OPENCLAUDE_AUTONOMY by default, while routePolicy/telemetry/contextBudget change routing, telemetry, and masking defaults; this is policy, not cleanup. Get explicit maintainer approval or split these policy-default changes into a separate reviewed PR with a clear rationale and rollout plan.
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the autonomy routing, Ollama fleet, fallback, and safety changes.
Description check ✅ Passed The description mostly follows the template and includes summary, testing, and notes, but the Impact section is not explicit.
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.
Risk Surface Disclosed ✅ Passed Review flags provider-routing/startup/release-script risk surfaces and marks blockers, e.g. Bun runtime change and unguarded resolveForMessages crash path.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch feature/autonomy-phase1

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.

❤️ Share

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

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 lift

Autonomy resolution + telemetry fire on every getToolUseContext call, not once per turn.

getToolUseContext is called from many sites (onQueryImpl, handleBackgroundQuery, immediate/queued commands, onAgentSubmit, and inline in render for toolPermissionOverlay at line 4537). Each call re-runs resolveAutonomyForMessages with recordTelemetry: 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_select telemetry line gets appended to turns.jsonl for 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 getToolUseContext callers) and only pass recordTelemetry: true from 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

📥 Commits

Reviewing files that changed from the base of the PR and between 87c457c and b28b18e.

📒 Files selected for processing (55)
  • GUIA_USO.md
  • docs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.md
  • docs/superpowers/knowledge/2026-07-09-consistency-eval.md
  • docs/superpowers/knowledge/2026-07-09-ollama-first-fleet.md
  • docs/superpowers/knowledge/2026-07-09-phase1-shipped.md
  • docs/superpowers/knowledge/2026-07-09-phase2-health-fallback.md
  • docs/superpowers/knowledge/2026-07-09-phase5-context-budget.md
  • docs/superpowers/knowledge/README.md
  • docs/superpowers/knowledge/ROUTING_BASELINE.md
  • docs/superpowers/knowledge/SESSION_INSIGHTS_TEMPLATE.md
  • docs/superpowers/plans/2026-07-09-agent-performance-autonomy.md
  • docs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.md
  • docs/superpowers/specs/2026-07-09-phase6-hybrid-local-intelligence.md
  • package.json
  • scripts/apply-ollama-autonomy.ts
  • scripts/doctor-autonomy.ts
  • src/Tool.ts
  • src/commands.ts
  • src/commands/route/index.ts
  • src/commands/route/route.ts
  • src/query.ts
  • src/query/stopHooks.ts
  • src/screens/REPL.tsx
  • src/services/api/agentRouting.test.ts
  • src/services/api/agentRouting.ts
  • src/services/api/claude.ts
  • src/services/api/withRetry.ts
  • src/services/autonomy/circuitBreakers.test.ts
  • src/services/autonomy/circuitBreakers.ts
  • src/services/autonomy/circuitToolBridge.test.ts
  • src/services/autonomy/circuitToolBridge.ts
  • src/services/autonomy/complexityClassifier.test.ts
  • src/services/autonomy/complexityClassifier.ts
  • src/services/autonomy/consistency.integration.test.ts
  • src/services/autonomy/contextBudget.test.ts
  • src/services/autonomy/contextBudget.ts
  • src/services/autonomy/index.ts
  • src/services/autonomy/providerFallback.test.ts
  • src/services/autonomy/providerFallback.ts
  • src/services/autonomy/providerHealth.test.ts
  • src/services/autonomy/providerHealth.ts
  • src/services/autonomy/resolveForMessages.test.ts
  • src/services/autonomy/resolveForMessages.ts
  • src/services/autonomy/routePolicy.test.ts
  • src/services/autonomy/routePolicy.ts
  • src/services/autonomy/sessionInsights.ts
  • src/services/autonomy/taskSignals.ts
  • src/services/autonomy/telemetry.test.ts
  • src/services/autonomy/telemetry.ts
  • src/services/tools/StreamingToolExecutor.ts
  • src/services/tools/toolOrchestration.ts
  • src/tools/AgentTool/runAgent.ts
  • src/utils/settings/types.ts
  • src/utils/toolResultStorage.ts
  • start-ollama.ps1
📜 Review details
🧰 Additional context used
📓 Path-based instructions (8)
**

⚙️ CodeRabbit configuration file

**: # AGENTS.md - AI Agent Coding Guide

This 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:

  • chalk for terminal color.
  • commander for CLI argument parsing.
  • execa for 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.md
  • src/services/autonomy/complexityClassifier.test.ts
  • docs/superpowers/knowledge/2026-07-09-consistency-eval.md
  • docs/superpowers/knowledge/2026-07-09-ollama-first-fleet.md
  • docs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.md
  • src/services/autonomy/circuitBreakers.test.ts
  • src/services/autonomy/resolveForMessages.test.ts
  • scripts/doctor-autonomy.ts
  • docs/superpowers/knowledge/2026-07-09-phase5-context-budget.md
  • src/commands.ts
  • src/services/autonomy/providerHealth.test.ts
  • src/query.ts
  • src/services/autonomy/providerFallback.test.ts
  • src/query/stopHooks.ts
  • docs/superpowers/knowledge/README.md
  • docs/superpowers/knowledge/2026-07-09-phase2-health-fallback.md
  • docs/superpowers/knowledge/2026-07-09-phase1-shipped.md
  • src/services/autonomy/circuitToolBridge.test.ts
  • src/tools/AgentTool/runAgent.ts
  • src/Tool.ts
  • src/services/autonomy/telemetry.test.ts
  • src/services/autonomy/routePolicy.test.ts
  • package.json
  • src/services/api/agentRouting.test.ts
  • src/services/autonomy/taskSignals.ts
  • docs/superpowers/knowledge/ROUTING_BASELINE.md
  • src/commands/route/route.ts
  • src/utils/settings/types.ts
  • src/services/autonomy/circuitBreakers.ts
  • src/services/autonomy/sessionInsights.ts
  • src/commands/route/index.ts
  • src/services/autonomy/index.ts
  • docs/superpowers/plans/2026-07-09-agent-performance-autonomy.md
  • src/services/autonomy/complexityClassifier.ts
  • src/services/autonomy/contextBudget.test.ts
  • src/services/autonomy/resolveForMessages.ts
  • src/screens/REPL.tsx
  • scripts/apply-ollama-autonomy.ts
  • src/services/tools/toolOrchestration.ts
  • src/utils/toolResultStorage.ts
  • src/services/api/claude.ts
  • start-ollama.ps1
  • src/services/autonomy/contextBudget.ts
  • src/services/api/agentRouting.ts
  • src/services/api/withRetry.ts
  • docs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.md
  • docs/superpowers/specs/2026-07-09-phase6-hybrid-local-intelligence.md
  • src/services/autonomy/routePolicy.ts
  • src/services/autonomy/consistency.integration.test.ts
  • src/services/autonomy/providerFallback.ts
  • GUIA_USO.md
  • src/services/autonomy/providerHealth.ts
  • src/services/tools/StreamingToolExecutor.ts
  • src/services/autonomy/telemetry.ts
  • src/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.md
  • src/services/autonomy/complexityClassifier.test.ts
  • docs/superpowers/knowledge/2026-07-09-consistency-eval.md
  • docs/superpowers/knowledge/2026-07-09-ollama-first-fleet.md
  • docs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.md
  • src/services/autonomy/circuitBreakers.test.ts
  • src/services/autonomy/resolveForMessages.test.ts
  • scripts/doctor-autonomy.ts
  • docs/superpowers/knowledge/2026-07-09-phase5-context-budget.md
  • src/commands.ts
  • src/services/autonomy/providerHealth.test.ts
  • src/query.ts
  • src/services/autonomy/providerFallback.test.ts
  • src/query/stopHooks.ts
  • docs/superpowers/knowledge/README.md
  • docs/superpowers/knowledge/2026-07-09-phase2-health-fallback.md
  • docs/superpowers/knowledge/2026-07-09-phase1-shipped.md
  • src/services/autonomy/circuitToolBridge.test.ts
  • src/tools/AgentTool/runAgent.ts
  • src/Tool.ts
  • src/services/autonomy/telemetry.test.ts
  • src/services/autonomy/routePolicy.test.ts
  • package.json
  • src/services/api/agentRouting.test.ts
  • src/services/autonomy/taskSignals.ts
  • docs/superpowers/knowledge/ROUTING_BASELINE.md
  • src/commands/route/route.ts
  • src/utils/settings/types.ts
  • src/services/autonomy/circuitBreakers.ts
  • src/services/autonomy/sessionInsights.ts
  • src/commands/route/index.ts
  • src/services/autonomy/index.ts
  • docs/superpowers/plans/2026-07-09-agent-performance-autonomy.md
  • src/services/autonomy/complexityClassifier.ts
  • src/services/autonomy/contextBudget.test.ts
  • src/services/autonomy/resolveForMessages.ts
  • src/screens/REPL.tsx
  • scripts/apply-ollama-autonomy.ts
  • src/services/tools/toolOrchestration.ts
  • src/utils/toolResultStorage.ts
  • src/services/api/claude.ts
  • start-ollama.ps1
  • src/services/autonomy/contextBudget.ts
  • src/services/api/agentRouting.ts
  • src/services/api/withRetry.ts
  • docs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.md
  • docs/superpowers/specs/2026-07-09-phase6-hybrid-local-intelligence.md
  • src/services/autonomy/routePolicy.ts
  • src/services/autonomy/consistency.integration.test.ts
  • src/services/autonomy/providerFallback.ts
  • GUIA_USO.md
  • src/services/autonomy/providerHealth.ts
  • src/services/tools/StreamingToolExecutor.ts
  • src/services/autonomy/telemetry.ts
  • src/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.md
  • docs/superpowers/knowledge/2026-07-09-consistency-eval.md
  • docs/superpowers/knowledge/2026-07-09-ollama-first-fleet.md
  • docs/superpowers/knowledge/2026-07-09-STOP-AND-TEST.md
  • docs/superpowers/knowledge/2026-07-09-phase5-context-budget.md
  • docs/superpowers/knowledge/README.md
  • docs/superpowers/knowledge/2026-07-09-phase2-health-fallback.md
  • docs/superpowers/knowledge/2026-07-09-phase1-shipped.md
  • docs/superpowers/knowledge/ROUTING_BASELINE.md
  • docs/superpowers/plans/2026-07-09-agent-performance-autonomy.md
  • docs/superpowers/specs/2026-07-09-agent-performance-autonomy-design.md
  • docs/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.ts
  • src/services/autonomy/circuitBreakers.test.ts
  • src/services/autonomy/resolveForMessages.test.ts
  • scripts/doctor-autonomy.ts
  • src/commands.ts
  • src/services/autonomy/providerHealth.test.ts
  • src/query.ts
  • src/services/autonomy/providerFallback.test.ts
  • src/query/stopHooks.ts
  • src/services/autonomy/circuitToolBridge.test.ts
  • src/tools/AgentTool/runAgent.ts
  • src/Tool.ts
  • src/services/autonomy/telemetry.test.ts
  • src/services/autonomy/routePolicy.test.ts
  • src/services/api/agentRouting.test.ts
  • src/services/autonomy/taskSignals.ts
  • src/commands/route/route.ts
  • src/utils/settings/types.ts
  • src/services/autonomy/circuitBreakers.ts
  • src/services/autonomy/sessionInsights.ts
  • src/commands/route/index.ts
  • src/services/autonomy/index.ts
  • src/services/autonomy/complexityClassifier.ts
  • src/services/autonomy/contextBudget.test.ts
  • src/services/autonomy/resolveForMessages.ts
  • src/screens/REPL.tsx
  • scripts/apply-ollama-autonomy.ts
  • src/services/tools/toolOrchestration.ts
  • src/utils/toolResultStorage.ts
  • src/services/api/claude.ts
  • src/services/autonomy/contextBudget.ts
  • src/services/api/agentRouting.ts
  • src/services/api/withRetry.ts
  • src/services/autonomy/routePolicy.ts
  • src/services/autonomy/consistency.integration.test.ts
  • src/services/autonomy/providerFallback.ts
  • src/services/autonomy/providerHealth.ts
  • src/services/tools/StreamingToolExecutor.ts
  • src/services/autonomy/telemetry.ts
  • src/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.ts
  • src/services/autonomy/circuitBreakers.test.ts
  • src/services/autonomy/resolveForMessages.test.ts
  • src/services/autonomy/providerHealth.test.ts
  • src/services/autonomy/providerFallback.test.ts
  • src/services/autonomy/circuitToolBridge.test.ts
  • src/services/autonomy/telemetry.test.ts
  • src/services/autonomy/routePolicy.test.ts
  • src/services/api/agentRouting.test.ts
  • src/services/autonomy/contextBudget.test.ts
  • src/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.ts
  • package.json
  • scripts/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.ts
  • src/services/api/claude.ts
  • src/services/api/agentRouting.ts
  • src/services/api/withRetry.ts
🪛 LanguageTool
docs/superpowers/knowledge/SESSION_INSIGHTS_TEMPLATE.md

[locale-violation] ~1-1: “TEMPLATE” é um estrangeirismo. É preferível dizer “modelo”.
Context: # Session Insight — TEMPLATE Copiar para `
/.openclaude/insights/<s...

(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 Quality

Same lazy require() pattern as resolveForMessages.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 & Privacy

No action needed on .env.openrouter. .gitignore already ignores .env and .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 Quality

Confirm the runtime for these lazy imports. If this file can execute under Node ESM, bare require() will hit the catch path and silently disable insights/session IDs unless Bun rewrites it in the production bundle. Use import() or createRequire if 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 via beforeEach resets.


118-133: 🎯 Functional Correctness

Drop this warning about an empty trivial fallback chain. resolveTaskRoute uses fallbackChains.default when fallbackChains.trivial is missing, so qwen2.5:7b can 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/FileWrite don’t affect this bridge path. extractToolObservation() only sees Edit/Write/NotebookEdit, and the file-edit/write tool names are still exported as Edit and Write. The extra EDIT_TOOLS entries 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 Quality

No 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 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

Comment thread GUIA_USO.md
Comment on lines +20 to +24
| Requisito | Versao Minima | Verificar |
| --------- | ------------- | ------------------ |
| Node.js | 20+ | `node --version` |
| Ollama | qualquer | `ollama --version` |
| Bun (dev) | 1.3.11+ | `bun --version` |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Suggested change
| 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

Comment thread GUIA_USO.md
Comment on lines +270 to +289

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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Stray content and editing artifacts in the "Trocar Modelo" section.

  • Line 271: ollama run kimi-k2.6:nuvem is outside a code block — appears to be a stray command.
  • Line 277: ESTA inside 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.

Comment thread package.json
"scripts": {
"build": "bun run scripts/build.ts",
"dev": "bun run build && node dist/cli.mjs",
"dev": "bun run build && bun dist/cli.mjs",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 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

Comment on lines +33 to +34
const raw = readFileSync(settingsPath, 'utf8')
const settings = JSON.parse(raw) as Record<string, unknown>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 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.

Suggested change
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.

Comment on lines +64 to +67
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Comment on lines +50 to +56
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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Suggested change
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.

Comment on lines +33 to +34
const VISION_RE =
/\b(screenshot|imagem|image|print|foto|photo|ui mock|wireframe|diagrama visual)\b/i

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Suggested change
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.

Comment on lines +89 to +109
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 []
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🚀 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.

Comment thread start-ollama.ps1
Comment on lines +1 to +15
# ============================================================
# 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
# ============================================================

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 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

@jatmn

jatmn commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

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:

  1. A narrowly scoped, opt-in routing-policy implementation with clear precedence rules and tests.
  2. Provider health and fallback behavior, with its own runtime and failure-path coverage.
  3. Tool-loop/circuit-breaker behavior, tested across complete agent turns.
  4. Any user-settings or launcher changes, designed to preserve existing configuration and require explicit opt-in.
  5. Focused documentation for each accepted feature; keep future design and planning material separate.

Each PR should rebase on current main, have a single clear goal, preserve user configuration by default, and include focused validation for the path it changes. That will make the work much easier to review and substantially safer to merge.

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.

@jatmn jatmn closed this Jul 9, 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.

2 participants