diff --git a/README.md b/README.md index 4f97ea2..65d7a24 100644 --- a/README.md +++ b/README.md @@ -519,8 +519,10 @@ description: One line the router uses to decide relevance. # Run even when the router would skip this agent. alwaysRun: true # Override the default model. -model: anthropic/claude-haiku-4-5 +model: anthropic/claude-opus-5-5 temperature: 0.1 +# How much reasoning each pass spends: low, medium, high, xhigh or max. +effort: high paths: ["packages/ios/**", "**/*.swift"] --- @@ -534,6 +536,19 @@ comment (and in the terminal) with the fix, and `ecr doctor` fails on them: frontmatter below an HTML comment, a byte-order mark or blank lines (all its keys are ignored), and a comment that breaks `alwaysRun`, `model` or `temperature`. +`effort` sets how much reasoning the model spends on that agent's passes. It works +on `anthropic/…`, `openai/…` (or an `upstream: "openai"` alias), Gemini 3 and later +on `google/…` or `google-vertex/…` (only `low`, `medium` or `high`), and `xai/…` +models. For other models the review prints a note and ignores it. Leave it out to +use the model's default. A higher level costs more and takes longer, so set it on +the agent that needs depth (a correctness reviewer that must trace callers), not on +every agent. ecr does not check which levels a model supports: a model can ignore a +level (Claude Haiku 4.5), and a provider can reject one, which fails that agent's +passes. A value that is not a level is listed under **Review setup**, and the agent +runs at the default. Only reviewer files take `effort`, and an agent file named +after a built-in pass (for example `verifier.md`) gets none; the review note says +to rename it. + `paths` limits an agent to the changes it covers. It takes a list of repo-relative globs in the routing dialect: `*` stays within a directory, `**` crosses directories, and a leading `**/` also matches files at the repo root. Write the diff --git a/llp/0006-config-schema-loading-routing.explainer.md b/llp/0006-config-schema-loading-routing.explainer.md index 989963c..9f62d40 100644 --- a/llp/0006-config-schema-loading-routing.explainer.md +++ b/llp/0006-config-schema-loading-routing.explainer.md @@ -217,6 +217,41 @@ is letters, digits and underscores joined by single hyphens. An agent without `m `mention` key, so its shape and review-cache key are unchanged [observed: `load.ts` `parseAgentMention`; `schema.ts` `MENTION_TARGET_RE`]. +## Agent Effort + +An agent file may set `effort: low|medium|high|xhigh|max` in its frontmatter. Depth is a per-agent +need (a correctness reviewer that must trace callers, not a conventions reviewer), and it costs time +and money, so it is a per-agent key and not a run-level flag. In an eval replay on one monorepo, a +correctness reviewer ended a pass after a median of 8 turns [observed]. + +- **Each engine maps the level to what its model takes.** The claude-code engine passes the CLI's + `--effort`. OpenCode passes it as a model option for the providers whose adapter takes a level: + OpenAI (and an `upstream: "openai"` alias), Gemini 3 and later on `google`/`google-vertex`, and + xAI (`opencodeEffortStyle`). Everything else gets no level: other providers and aliases, Claude + on Vertex (another adapter), Gemini 2.5 and older (they take a thinking budget, not a level), and + Gemini `xhigh`/`max` (the bundled Google adapter rejects them). The pinned OpenCode behavior was + checked against a mock endpoint [observed]; re-check it when the pins move. +- **ecr passes the level as written.** It does not check which levels a model supports; a model can + ignore a level, and a provider can reject one, which fails that agent's passes. +- **Only reviewers get a level.** Levels are looked up by agent id, so a reviewer file that shares + the id of a fixed pass (verifier, cross-cutting, adjudicator, stack-verifier, coordinator) or of + an OpenCode built-in agent (`compaction`, `title`, …) gets none, because the level would also reach + that pass. `effort` in `coordinator.md` or `shared.md` is a setup warning. +- **A note names every level that has no effect.** `selectReviewers` builds it after the `paths` + filter and the router, so it names only selected reviewers, with the fix. +- **The no-tools fallback does not run deeper.** On the claude-code engine, a timed-out pass retried + without tools runs at `min(level, medium)`. On OpenCode it keeps the agent's level, because a + model can reject a lower level that the author did not write. +- **A developer's OpenCode variant wins.** OpenCode applies a variant set on a same-named agent in the + developer's own OpenCode config after ecr's options. ecr does not clear it, because a variant can + carry other options too (for example a service tier). +- **It never stops a review.** An invalid value is a setup warning that does not repeat the value, + and the agent runs at the default. An absent key adds nothing to the agent, so its review-cache key + does not change. `REVIEWER_MODEL` keeps the level. +- **Not handled here.** In a routed scope with `enforceAgents`, per-agent warnings come from the + scope's own files (`mention` has the same gap). The shared frontmatter reader strips an unmatched + quote (`effort: "max` loads as `max`). + ## Budgets and Chunking Defaults `budget.totalPassesMinutes` defaults to 55, not the scaffolded workflow's full 90-minute timeout, diff --git a/src/__tests__/claude-code.test.ts b/src/__tests__/claude-code.test.ts index 5c25fae..4528983 100644 --- a/src/__tests__/claude-code.test.ts +++ b/src/__tests__/claude-code.test.ts @@ -7,6 +7,8 @@ import { describe, expect, it, test } from "bun:test"; import { assertClaudeModels, + agentEffortNote, + buildAgentEfforts, buildClaudeArgs, buildEngineMap, claudeActivities, @@ -37,7 +39,7 @@ import { import type { OpencodeHandle } from "../core/opencode.js"; import { parseReviewerOutput } from "../core/schema.js"; import { RateLimitWatch } from "../core/throttle.js"; -import type { AuthConfigEntry, LoadedConfig } from "../config/schema.js"; +import type { AuthConfigEntry, LoadedAgent, LoadedConfig } from "../config/schema.js"; const entry = (over: Partial): AuthConfigEntry => ({ provider: "anthropic", @@ -820,6 +822,249 @@ test("claudeTokenCredential: resolution order + oat/api-key classification", () expect(claudeTokenCredential(undefined, {})).toBeUndefined(); }); +test("buildClaudeArgs: passes --effort only when a level is given", () => { + const base = { model: "claude-opus-5", system: "SYS", cwd: "/work/repo" }; + expect(buildClaudeArgs(base)).not.toContain("--effort"); + const args = buildClaudeArgs({ ...base, effort: "high" }); + expect(args[args.indexOf("--effort") + 1]).toBe("high"); +}); + +test("runClaudePrompt: an agent's effort reaches its own passes and no other agent's", async () => { + const body = JSON.stringify({ + type: "result", + subtype: "success", + is_error: false, + result: "ok", + }); + const { bin, argsLog, cleanup } = await sequencedFakeClaude([body]); + try { + // A real run gives every reviewer its own models/tools entry (buildEngineMap); + // only `efforts` lacks one for an agent that sets no level. + const handle = testHandle(bin, { + models: { reviewer: "anthropic/claude-opus-5", constructor: "anthropic/claude-opus-5" }, + tools: { reviewer: ["read", "grep", "glob"], constructor: ["read", "grep", "glob"] }, + efforts: new Map([["reviewer", "xhigh"]]), + }); + await runClaudePrompt(handle, { agent: "reviewer", system: "SYS", text: "hi", title: "t" }); + await runClaudePrompt(handle, { agent: "verifier", system: "SYS", text: "hi", title: "t" }); + // An id that names an Object.prototype member must not read an inherited value. + await runClaudePrompt(handle, { agent: "constructor", system: "SYS", text: "hi", title: "t" }); + const reviewer = (await argsLog(1)).split("\n"); + expect(reviewer[reviewer.indexOf("--effort") + 1]).toBe("xhigh"); + expect((await argsLog(2)).split("\n")).not.toContain("--effort"); + expect((await argsLog(3)).split("\n")).not.toContain("--effort"); + // The no-tools fallback of a timed-out pass runs at the level capped at medium. + await runClaudePrompt(handle, { + agent: "reviewer", + system: "SYS", + text: "hi", + title: "t", + maxToolCalls: 0, + }); + const fallback = (await argsLog(4)).split("\n"); + expect(fallback[fallback.indexOf("--effort") + 1]).toBe("medium"); + } finally { + await cleanup(); + } +}); + +test("buildAgentEfforts: no entry for a reviewer that shares a fixed role's id", () => { + const fixedRoles = ["coordinator", "verifier", "cross-cutting", "adjudicator", "stack-verifier"]; + const config = { + agents: [ + { id: "correctness", effort: "high" }, + ...fixedRoles.map((id) => ({ id, effort: "max" })), + // An OpenCode built-in id keeps its level on the claude-code engine. + { id: "compaction", effort: "high" }, + { id: "constructor" }, + ], + } as unknown as LoadedConfig; + const efforts = buildAgentEfforts(config); + expect([...efforts]).toEqual([ + ["correctness", "high"], + ["compaction", "high"], + ]); + expect(efforts.get("constructor")).toBeUndefined(); +}); + +test("agentEffortNote: names the agents whose effort an OpenCode-routed model ignores", () => { + const agents = [ + { id: "a", effort: "high" }, + { id: "b", effort: "low" }, + { id: "c" }, + ] as unknown as LoadedAgent[]; + expect( + agentEffortNote(agents, { a: "claude-code", b: "claude-code", c: "opencode" }, []), + ).toBeNull(); + const note = agentEffortNote(agents, { a: "claude-code", b: "opencode", c: "opencode" }, []); + expect(note).toContain("has no effect for b:"); + expect(note).not.toContain("for a"); +}); + +test("agentEffortNote: an agent that does not run in this review is not named", () => { + // The caller passes the reviewers left after the `paths` filter and the router. Here + // `ios` (OpenCode) was routed out and agents/verifier.md was excluded by its paths, + // although the engine map still has entries for both ids. + const selected = [{ id: "alpha", effort: "high" }] as unknown as LoadedAgent[]; + expect( + agentEffortNote( + selected, + { alpha: "claude-code", ios: "opencode", verifier: "claude-code" }, + [], + ), + ).toBeNull(); +}); + +test("agentEffortNote: OpenAI, Google and xAI models take a level through OpenCode; others do not", () => { + const agents = [ + { id: "astra", effort: "high", model: "openai/gpt-6.2-astra" }, + { id: "pro", effort: "high", model: "openai-api/gpt-5.5-pro" }, + { id: "neon", effort: "high", model: "google/gemini-4-neon" }, + { id: "vertex", effort: "high", model: "google-vertex/gemini-4-neon" }, + { id: "grok", effort: "high", model: "xai/grok-4.7" }, + { id: "muse", effort: "high", model: "meta/muse-spark-1.3" }, + ] as unknown as LoadedAgent[]; + const engineOf = { + astra: "opencode", + pro: "opencode", + neon: "opencode", + vertex: "opencode", + grok: "opencode", + muse: "opencode", + } as const; + const auth = [ + { provider: "openai-api", mode: "api-key", tokenEnv: "OPENAI_API_KEY", upstream: "openai" }, + ] as unknown as AuthConfigEntry[]; + const named = (note: string | null) => note?.match(/has no effect for ([^:]+):/)?.[1]; + const note = agentEffortNote(agents, engineOf, auth); + expect(note).toContain( + "the model of each runs through OpenCode on a provider ecr passes no level to (ecr passes one only for `anthropic/…`", + ); + expect(note).toContain( + '(ecr passes one only for `anthropic/…`, `openai/…` (or an `upstream: "openai"` alias), `google/…` or `google-vertex/…` (Gemini 3 and later), or `xai/…`)', + ); + expect(named(note)).toBe("muse"); + // Without the alias's auth entry, `openai-api` is not known to be OpenAI. + expect(named(agentEffortNote(agents, engineOf, []))).toBe("pro, muse"); +}); + +test("agentEffortNote: a Gemini 2.5 reviewer is told it takes a budget, once", () => { + const agents = [ + { id: "flash", effort: "high", model: "google-vertex/gemini-2.5-flash" }, + ] as unknown as LoadedAgent[]; + const note = agentEffortNote(agents, { flash: "opencode" }, []); + expect(note).toContain( + "has no effect for flash: Gemini 2.5 and older models take a thinking budget", + ); + expect(note).toContain("Fix: use a Gemini 3 or later model with low, medium or high"); + expect(note?.split("has no effect").length).toBe(2); +}); + +test("agentEffortNote: a Google level the pinned adapter rejects is named with the levels it takes", () => { + const agents = [ + { id: "neon", effort: "xhigh", model: "google/gemini-4-neon" }, + { id: "vertex", effort: "max", model: "google-vertex/gemini-4-neon" }, + { id: "ok", effort: "medium", model: "google/gemini-4-neon" }, + ] as unknown as LoadedAgent[]; + const note = agentEffortNote( + agents, + { neon: "opencode", vertex: "opencode", ok: "opencode" }, + [], + ); + expect(note).toContain("has no effect for neon (xhigh), vertex (max): OpenCode's Google adapter"); + expect(note).toContain("takes only low, medium, high"); + expect(note).toContain("Fix: use one of those levels"); + expect(note).not.toContain("ok ("); +}); + +test("agentEffortNote: a Google-upstream alias takes no level and is named", () => { + const agents = [ + { id: "gem", effort: "high", model: "gemini-api/gemini-4-neon" }, + ] as unknown as LoadedAgent[]; + const auth = [ + { provider: "gemini-api", mode: "api-key", tokenEnv: "GEMINI_KEY_2", upstream: "google" }, + ] as unknown as AuthConfigEntry[]; + expect(agentEffortNote(agents, { gem: "opencode" }, auth)).toContain( + "has no effect for gem: the model of each runs through OpenCode on a provider ecr passes no level to", + ); +}); + +test("agentEffortNote: a fixed-role reviewer on Google xhigh is also told the levels Google takes", () => { + const agents = [ + { id: "verifier", effort: "xhigh", model: "google/gemini-4-neon" }, + ] as unknown as LoadedAgent[]; + const note = agentEffortNote(agents, { verifier: "claude-code" }, []); + expect(note).toContain("Fix: rename the agent file, and give verifier one of low, medium, high"); +}); + +test("agentEffortNote: an OpenCode reviewer named after an OpenCode built-in agent is told to rename", () => { + const agents = [ + { id: "compaction", effort: "xhigh", model: "openai/gpt-6.2-astra" }, + ] as unknown as LoadedAgent[]; + const note = agentEffortNote(agents, { compaction: "opencode" }, []); + expect(note).toContain("has no effect for compaction: the id is also an OpenCode built-in agent"); + expect(note).toContain("Fix: rename the agent file"); + expect(note).not.toContain("runs through OpenCode on a provider"); + // On the claude-code engine the level does apply, so there is no note. + expect(agentEffortNote(agents, { compaction: "claude-code" }, [])).toBeNull(); +}); + +test("agentEffortNote: an OpenCode built-in id on Google max is also told the levels Google takes", () => { + const agents = [ + { id: "compaction", effort: "max", model: "google/gemini-4-neon" }, + { id: "title", effort: "high", model: "meta/muse-spark-1.3" }, + ] as unknown as LoadedAgent[]; + const note = agentEffortNote(agents, { compaction: "opencode", title: "opencode" }, []); + expect(note).toContain( + "has no effect for compaction, title: the id is also an OpenCode built-in agent", + ); + expect(note).toContain("and run title on a model that takes a level"); + expect(note).toContain("and give compaction one of low, medium, high"); + // One note only: the built-in id is not also listed as a plain OpenCode or Google case. + expect(note?.split("has no effect").length).toBe(2); +}); + +test("agentEffortNote: a fixed-role reviewer on OpenAI is told only to rename", () => { + const agents = [ + { id: "verifier", effort: "max", model: "openai/gpt-6.2-astra" }, + ] as unknown as LoadedAgent[]; + const note = agentEffortNote(agents, { verifier: "claude-code" }, []); + expect(note).toContain("Fix: rename the agent file"); + expect(note?.endsWith("Fix: rename the agent file")).toBe(true); +}); + +test("agentEffortNote: reports both reasons in one note", () => { + const agents = [ + { id: "ios", effort: "high" }, + { id: "verifier", effort: "max" }, + ] as unknown as LoadedAgent[]; + const note = agentEffortNote(agents, { ios: "opencode", verifier: "claude-code" }, []); + expect(note).toContain("has no effect for ios: the model of each runs through OpenCode"); + expect(note).toContain("; `effort` has no effect for verifier: the id is also a built-in pass"); +}); + +test("agentEffortNote: a fixed-role reviewer on a model that takes no level is told to change the model too", () => { + const agents = [ + { id: "verifier", effort: "max", model: "meta/muse-spark-1.3" }, + { id: "coordinator", effort: "high", model: "anthropic/claude-opus-5-5" }, + ] as unknown as LoadedAgent[]; + // The engine map describes the built-in passes (claude here), not the reviewer files. + const note = agentEffortNote(agents, { verifier: "claude-code", coordinator: "claude-code" }, []); + expect(note).toContain( + "Fix: rename the agent file, and run verifier on a model that takes a level", + ); + expect(note).toContain("`REVIEWER_MODEL` when that is set"); + expect(note).not.toContain("run verifier, coordinator"); +}); + +test("agentEffortNote: a reviewer that shares a fixed role's id is told to rename", () => { + const agents = [{ id: "verifier", effort: "max" }] as unknown as LoadedAgent[]; + const note = agentEffortNote(agents, { verifier: "opencode" }, []); + expect(note).toContain("has no effect for verifier: the id is also a built-in pass"); + expect(note).toContain("Fix: rename the agent file"); + expect(note).not.toContain("runs through OpenCode"); +}); + test("claudeTemperatureNote: flags non-default temperatures on CLAUDE-ROUTED passes only", () => { const config = (agentTemp: number, coordTemp: number): LoadedConfig => ({ @@ -955,6 +1200,16 @@ test("startClaudeCode: childEnv is an allowlist (forbidden ambient secrets exclu // sk-ant-oat… classifies as oauth ⇒ CLAUDE_CODE_OAUTH_TOKEN, never ANTHROPIC_API_KEY. expect(handle.childEnv.CLAUDE_CODE_OAUTH_TOKEN).toBe(oat); expect(handle.childEnv.ANTHROPIC_API_KEY).toBeUndefined(); + // No agent sets `effort`, so the handle has no efforts map. + expect(handle.efforts).toBeUndefined(); + const withEffort = await startClaudeCode({ + ...config, + agents: [ + { id: "reviewer", model: "anthropic/claude-opus-5", tools: {}, effort: "high" }, + { id: "verifier", model: "anthropic/claude-opus-5", tools: {}, effort: "max" }, + ], + } as unknown as LoadedConfig); + expect([...(withEffort.efforts ?? [])]).toEqual([["reviewer", "high"]]); } finally { for (const [key, value] of Object.entries(saved)) { if (value === undefined) { diff --git a/src/__tests__/config-load.test.ts b/src/__tests__/config-load.test.ts index 9bcc841..f25bfdd 100644 --- a/src/__tests__/config-load.test.ts +++ b/src/__tests__/config-load.test.ts @@ -10,6 +10,7 @@ import { stripJsonComments, stripTrailingCommas, } from "../config/load.js"; +import { fallbackEffort } from "../config/schema.js"; test("parseFrontmatter: parses scalar keys + returns body without frontmatter", () => { const { data, body } = parseFrontmatter("---\nmodel: x\nalwaysRun: true\n---\n# Body\ntext"); @@ -299,6 +300,64 @@ test("loadReviewConfig: `includeSuggestions` loads as a floor, with a deprecatio } }); +test("loadReviewConfig: front-matter `effort` loads onto the agent; no `effort` adds no key", async () => { + const root = await configDirWithAgent("---\neffort: High\n---\nIOS"); + try { + const config = await loadReviewConfig(root); + const ios = config.agents.find((agent) => agent.id === "ios")!; + const plain = config.agents.find((agent) => agent.id === "plain")!; + expect(ios.effort).toBe("high"); + // Absent, not undefined: an agent without `effort` keeps its review-cache key. + expect("effort" in plain).toBe(false); + expect("setupWarnings" in config).toBe(false); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("loadReviewConfig: an invalid `effort` is a warning, and the agent runs at the default", async () => { + for (const line of ["effort: extreme", "effort:", "effort: high # deep trace"]) { + const root = await configDirWithAgent(`---\n${line}\n---\nIOS`); + try { + const config = await loadReviewConfig(root); + const ios = config.agents.find((agent) => agent.id === "ios")!; + expect("effort" in ios, line).toBe(false); + expect(config.setupWarnings, line).toHaveLength(1); + const [warning] = config.setupWarnings!; + expect(warning).toContain(path.join(CONFIG_DIRNAME, "agents", "ios.md")); + expect(warning).toContain("is not an effort level"); + // The raw value is never repeated into the review comment. + expect(warning, line).not.toContain("extreme"); + expect(warning, line).not.toContain("deep trace"); + expect(warning).toContain("low, medium, high, xhigh, max"); + } finally { + await rm(root, { recursive: true, force: true }); + } + } +}); + +test("loadReviewConfig: `effort` in coordinator.md or shared.md is a warning, not silently ignored", async () => { + const root = await configDirWithAgent("IOS", "---\neffort: high\n---\nCoordinator prompt."); + try { + await writeFile( + path.join(root, CONFIG_DIRNAME, "shared.md"), + "---\neffort: max\n---\nShared prompt.", + "utf8", + ); + const config = await loadReviewConfig(root); + expect(config.setupWarnings).toHaveLength(2); + for (const file of ["shared.md", "coordinator.md"]) { + const warning = config.setupWarnings!.find((w) => + w.includes(path.join(CONFIG_DIRNAME, file)), + ); + expect(warning, file).toContain("is read only in agents/*.md reviewer files"); + expect(warning, file).toContain("Fix: remove `effort` from this file."); + } + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + test("loadReviewConfig: front-matter `mention` loads GitHub logins and teams onto the agent", async () => { const root = await configDirWithAgent( '---\nmention:\n - amandeepmittal\n - "@expo/docs"\n---\nIOS', @@ -367,3 +426,11 @@ test("loadReviewConfig: reads the PR template comments from the repository root" await rm(root, { recursive: true, force: true }); } }); + +test("fallbackEffort: the agent's level, capped at medium", () => { + expect(fallbackEffort("low")).toBe("low"); + expect(fallbackEffort("medium")).toBe("medium"); + expect(fallbackEffort("high")).toBe("medium"); + expect(fallbackEffort("xhigh")).toBe("medium"); + expect(fallbackEffort("max")).toBe("medium"); +}); diff --git a/src/__tests__/opencode.test.ts b/src/__tests__/opencode.test.ts index 791f153..71c62eb 100644 --- a/src/__tests__/opencode.test.ts +++ b/src/__tests__/opencode.test.ts @@ -18,6 +18,10 @@ import { serverStopped, STACK_VERIFIER_AGENT, META_MODEL_API_BASE_URL, + opencodeEffortStyle, + OPENCODE_BUILTIN_AGENTS, + VERIFIER_AGENT, + CROSS_CUTTING_AGENT, } from "../core/opencode.js"; import type { OpencodeHandle } from "../core/opencode.js"; import type { ClaudeCodeHandle } from "../core/claude-code.js"; @@ -58,7 +62,7 @@ test("resolveEngineDispatch: per-agent router picks the right engine and claude /** Minimal LoadedConfig for buildOpencodeConfig tests. */ function configWith(overrides: { - agents?: Array<{ id: string; model: string }>; + agents?: Array<{ id: string; model: string; effort?: string }>; coordinatorModel?: string; auth?: unknown[]; }): LoadedConfig { @@ -689,3 +693,118 @@ describe("Recording an OpenCode pass for the session archive", () => { expect(handle.capture?.count).toBe(0); }, 20_000); }); + +test("opencodeEffortStyle: OpenAI, Google and xAI families take a level; others do not", () => { + const alias = [ + { provider: "openai-api", mode: "api-key", tokenEnv: "OPENAI_API_KEY", upstream: "openai" }, + { provider: "claude-api", mode: "api-key", tokenEnv: "ANTHROPIC_KEY_2", upstream: "anthropic" }, + // ecr builds this alias with the OpenAI-compatible adapter, not Google's. + { provider: "gemini-api", mode: "api-key", tokenEnv: "GEMINI_KEY_2", upstream: "google" }, + // Also OpenAI-compatible, not xAI's adapter. + { provider: "xai-api", mode: "api-key", tokenEnv: "XAI_KEY_2", upstream: "xai" }, + ] as unknown as LoadedConfig["auth"]; + expect(opencodeEffortStyle("openai/gpt-6.2-astra", [])).toBe("openai"); + expect(opencodeEffortStyle("openai-api/gpt-5.5-pro", alias)).toBe("openai"); + expect(opencodeEffortStyle("openai-api/gpt-5.5-pro", [])).toBeNull(); + expect(opencodeEffortStyle("google/gemini-4-neon", [])).toBe("google"); + expect(opencodeEffortStyle("google-vertex/gemini-4-neon", [])).toBe("google"); + expect(opencodeEffortStyle("claude-api/claude-opus-5-5", alias)).toBeNull(); + expect(opencodeEffortStyle("gemini-api/gemini-4-neon", alias)).toBeNull(); + expect(opencodeEffortStyle("xai-api/grok-4.7", alias)).toBeNull(); + expect(opencodeEffortStyle("meta/muse-spark-1.3", [])).toBeNull(); + expect(opencodeEffortStyle("gpt-6.2-astra", [])).toBeNull(); + expect(opencodeEffortStyle("xai/grok-4.7", [])).toBe("xai"); + // Gemini 2.5 and older take a thinking budget, not a level. + expect(opencodeEffortStyle("google/gemini-2.5-flash", [])).toBe("google-budget"); + expect(opencodeEffortStyle("google-vertex/gemini-2.5-pro", [])).toBe("google-budget"); + expect(opencodeEffortStyle("google/gemini-1.5-pro", [])).toBe("google-budget"); + expect(opencodeEffortStyle("google/gemini-3-pro", [])).toBe("google"); + // Vertex also serves Claude, on the Anthropic adapter, which ignores thinkingConfig. + expect(opencodeEffortStyle("google-vertex/claude-opus-5-5@default", [])).toBeNull(); +}); + +test("buildOpencodeConfig passes a reviewer's effort as its provider's option, and only a reviewer's", () => { + const opencode = buildOpencodeConfig( + configWith({ + agents: [ + { id: "astra", model: "openai/gpt-6.2-astra", effort: "xhigh" }, + { id: "neon", model: "google/gemini-4-neon", effort: "low" }, + { id: "neon-x", model: "google/gemini-4-neon", effort: "xhigh" }, + { id: "vertex-max", model: "google-vertex/gemini-4-neon", effort: "max" }, + { id: "muse", model: "meta/muse-spark-1.3", effort: "high" }, + { id: "plain", model: "openai/gpt-6.2-astra" }, + { id: "verifier", model: "openai/gpt-6.2-astra", effort: "max" }, + ], + }), + ) as { agent: Record> }; + expect(opencode.agent.astra!.reasoningEffort).toBe("xhigh"); + expect(opencode.agent.astra!.thinkingConfig).toBeUndefined(); + expect(opencode.agent.neon!.thinkingConfig).toEqual({ thinkingLevel: "low" }); + expect(opencode.agent.neon!.reasoningEffort).toBeUndefined(); + // The pinned Google adapter rejects xhigh and max, so they get no key at all. + for (const id of [ + "neon-x", + "vertex-max", + "muse", + "plain", + VERIFIER_AGENT, + CROSS_CUTTING_AGENT, + "coordinator", + ]) { + expect(opencode.agent[id]!.reasoningEffort, id).toBeUndefined(); + expect(opencode.agent[id]!.thinkingConfig, id).toBeUndefined(); + } +}); + +test("buildOpencodeConfig gives no level to a reviewer that shares an OpenCode built-in agent id", () => { + const opencode = buildOpencodeConfig( + configWith({ + agents: [ + { id: "compaction", model: "openai/gpt-6.2-astra", effort: "xhigh" }, + { id: "title", model: "google/gemini-4-neon", effort: "low" }, + { id: "astra", model: "openai/gpt-6.2-astra", effort: "xhigh" }, + ], + }), + ) as { agent: Record> }; + // OpenCode also runs these for other sessions (compaction, titles), so no level there. + expect(opencode.agent.compaction!.reasoningEffort).toBeUndefined(); + expect(opencode.agent.title!.thinkingConfig).toBeUndefined(); + expect(opencode.agent.astra!.reasoningEffort).toBe("xhigh"); + expect([...OPENCODE_BUILTIN_AGENTS].sort()).toEqual([ + "build", + "compaction", + "explore", + "general", + "plan", + "summary", + "title", + ]); +}); + +test("buildOpencodeConfig passes a Grok reviewer's level as reasoningEffort", () => { + const opencode = buildOpencodeConfig( + configWith({ agents: [{ id: "grok", model: "xai/grok-4.7", effort: "xhigh" }] }), + ) as { agent: Record> }; + expect(opencode.agent.grok!.reasoningEffort).toBe("xhigh"); + expect(opencode.agent.grok!.thinkingConfig).toBeUndefined(); +}); + +test("buildOpencodeConfig: no level for Gemini 2.5 or Claude on Vertex, and no variant override", () => { + const opencode = buildOpencodeConfig( + configWith({ + agents: [ + { id: "flash", model: "google-vertex/gemini-2.5-flash", effort: "high" }, + { id: "vertex-claude", model: "google-vertex/claude-opus-5-5@default", effort: "high" }, + { id: "neon", model: "google/gemini-4-neon", effort: "low" }, + { id: "astra", model: "openai/gpt-6.2-astra", effort: "xhigh" }, + ], + }), + ) as { agent: Record> }; + expect(opencode.agent.flash!.thinkingConfig).toBeUndefined(); + expect(opencode.agent["vertex-claude"]!.thinkingConfig).toBeUndefined(); + expect(opencode.agent.neon!.thinkingConfig).toEqual({ thinkingLevel: "low" }); + // ecr never clears a variant: one from the developer's OpenCode config keeps all its options. + for (const id of ["flash", "vertex-claude", "neon", "astra"]) { + expect("variant" in opencode.agent[id]!, id).toBe(false); + } +}); diff --git a/src/__tests__/review-internals.test.ts b/src/__tests__/review-internals.test.ts index 0d4275c..e611362 100644 --- a/src/__tests__/review-internals.test.ts +++ b/src/__tests__/review-internals.test.ts @@ -26,6 +26,7 @@ import { attachVerifierRejected, exportReviewSessions, runReview, + selectReviewers, } from "../core/review.js"; import type { AgentSummaryParts, ReviewRunOptions } from "../core/review.js"; import { resolveOpencodeCli } from "../core/opencode.js"; @@ -38,7 +39,7 @@ import { REVIEW_TRACE_BYTES_LIMIT, fingerprintFinding, } from "../core/schema.js"; -import type { LoadedConfig } from "../config/schema.js"; +import type { LoadedAgent, LoadedConfig } from "../config/schema.js"; import type { PatchWorkspaceFile } from "../core/noise.js"; import type { CoordinatorOutput, Finding, Severity } from "../core/schema.js"; @@ -929,3 +930,78 @@ describe("Exporting OpenCode sessions before the review closes", () => { expect(log).toEqual(["session store: export failed: the database is locked"]); }); }); + +describe("selectReviewers: the effort note names only selected reviewers", () => { + const alpha = { id: "alpha", effort: "high" } as unknown as LoadedAgent; + const ios = { id: "ios", effort: "high" } as unknown as LoadedAgent; + const engineOf = { alpha: "claude-code", ios: "opencode", verifier: "claude-code" } as const; + + it("does not name an OpenCode reviewer the router left out", async () => { + const lines: string[] = []; + const result = await selectReviewers({ + candidates: [alpha, ios], + route: async () => ({ agents: [alpha], routed: true }), + engineOf, + auth: [], + progress: (line) => lines.push(line), + }); + expect(result.selectedAgents.map((a) => a.id)).toEqual(["alpha"]); + expect(result.notRouted).toEqual(["ios"]); + expect(lines).toContain("Router selected: alpha"); + expect(lines.some((line) => line.includes("effort"))).toBe(false); + }); + + it("names an OpenCode reviewer that runs", async () => { + const lines: string[] = []; + await selectReviewers({ + candidates: [alpha, ios], + engineOf, + auth: [], + progress: (line) => lines.push(line), + }); + const note = lines.find((line) => line.startsWith("Note: `effort`")); + expect(note).toContain("has no effect for ios:"); + }); + + it("does not tell a routed-out agents/verifier.md to rename, but does when it runs", async () => { + const verifier = { id: "verifier", effort: "max" } as unknown as LoadedAgent; + const routedOut: string[] = []; + await selectReviewers({ + candidates: [alpha, verifier], + route: async () => ({ agents: [alpha], routed: true }), + engineOf, + auth: [], + progress: (line) => routedOut.push(line), + }); + expect(routedOut.some((line) => line.includes("effort"))).toBe(false); + + const selected: string[] = []; + await selectReviewers({ + candidates: [alpha, verifier], + route: async () => ({ agents: [alpha, verifier], routed: true }), + engineOf, + auth: [], + progress: (line) => selected.push(line), + }); + expect(selected.find((line) => line.startsWith("Note: `effort`"))).toContain( + "has no effect for verifier: the id is also a built-in pass", + ); + }); + + it("runs every candidate, and names a running OpenCode reviewer, when the router falls back", async () => { + const lines: string[] = []; + const result = await selectReviewers({ + candidates: [alpha, ios], + route: async () => ({ agents: [alpha, ios], routed: false }), + engineOf, + auth: [], + progress: (line) => lines.push(line), + }); + expect(result.selectedAgents.map((a) => a.id)).toEqual(["alpha", "ios"]); + expect(result.notRouted).toEqual([]); + expect(lines).toContain("Router unavailable; running all agents."); + expect(lines.find((line) => line.startsWith("Note: `effort`"))).toContain( + "has no effect for ios:", + ); + }); +}); diff --git a/src/config/load.ts b/src/config/load.ts index 29061b3..fb983fb 100644 --- a/src/config/load.ts +++ b/src/config/load.ts @@ -6,8 +6,13 @@ import { readdir, readFile } from "node:fs/promises"; import { existsSync } from "node:fs"; import path from "node:path"; -import { DEFAULT_MIN_SEVERITY, ReviewConfigSchema, ScopeReviewConfigSchema } from "./schema.js"; -import type { AuthConfigEntry } from "./schema.js"; +import { + AGENT_EFFORT_LEVELS, + DEFAULT_MIN_SEVERITY, + ReviewConfigSchema, + ScopeReviewConfigSchema, +} from "./schema.js"; +import type { AgentEffort, AuthConfigEntry } from "./schema.js"; import type { LoadedAgent, LoadedConfig, @@ -242,14 +247,28 @@ async function loadConfigDir( }; // shared.md is optional; the coordinator is required. - const sharedPromptText = existsSync(path.join(dir, "shared.md")) - ? (await readPrompt("shared.md")).body - : ""; + const sharedMd = existsSync(path.join(dir, "shared.md")) + ? await readPrompt("shared.md") + : undefined; + const sharedPromptText = sharedMd?.body ?? ""; if (!existsSync(path.join(dir, "coordinator.md"))) { throw new Error(`Missing ${CONFIG_DIRNAME}/coordinator.md`); } const coordinatorMd = await readPrompt("coordinator.md"); + // @ref LLP 0006#agent-effort [implements] — only reviewer files take `effort`; say so instead of ignoring it silently + for (const [file, md] of [ + ["shared.md", sharedMd], + ["coordinator.md", coordinatorMd], + ] as const) { + if (md?.data.effort !== undefined) { + setupWarnings.push( + `${path.join(label, file)}: \`effort\` is read only in agents/*.md reviewer files, so it ` + + "has no effect here; the built-in passes run at the default effort. Fix: remove " + + "`effort` from this file.", + ); + } + } // Every markdown file in agents/ is a reviewer agent (id = filename). const agentsDir = path.join(dir, "agents"); @@ -276,6 +295,13 @@ async function loadConfigDir( if (mentionWarning) { setupWarnings.push(mentionWarning); } + const { effort, warning: effortWarning } = parseAgentEffort( + md, + path.join(label, "agents", file), + ); + if (effortWarning) { + setupWarnings.push(effortWarning); + } agents.push({ id, description: md.data.description ?? "", @@ -288,6 +314,7 @@ async function loadConfigDir( // review-cache key) it had before the key existed. ...(paths ? { paths } : {}), ...(mention ? { mention } : {}), + ...(effort ? { effort } : {}), }); } @@ -640,6 +667,35 @@ function parseAgentPaths( return { paths: md.lists.paths }; } +/** + * The agent's `effort` level, or a setup warning that names the fix. A value that is + * not a level is ignored and the agent runs at the default effort; it never fails + * the load. + */ +// @ref LLP 0006#agent-effort [implements] — an invalid level warns and falls back, it never stops a review +function parseAgentEffort( + md: { data: Record }, + file: string, +): { effort?: AgentEffort; warning?: string } { + const raw = md.data.effort; + if (raw === undefined) { + return {}; + } + const value = raw.trim().toLowerCase(); + const effort = AGENT_EFFORT_LEVELS.find((level) => level === value); + if (effort) { + return { effort }; + } + return { + warning: + // The value is not repeated: a backtick in it would close the code span in the + // review comment, and a long one would go into the comment uncapped. + `${file}: \`effort\` is not an effort level, so the agent runs at the default ` + + `effort. Fix: write one of ${AGENT_EFFORT_LEVELS.join(", ")} with nothing after it ` + + "(a `# comment` goes on its own line), or remove `effort`.", + }; +} + /** * The agent's `mention` list without leading `@`s, or a setup warning that names the * fix. An entry that is not a login or team is left out with a warning, and the @@ -768,8 +824,8 @@ function frontmatterWarnings( if (hidden) { return [ `${file}: its frontmatter does not start on the first line (${hidden.cause}), so ` + - "every key in it is ignored, including `description`, `alwaysRun`, `model` and " + - `\`paths\`. Fix: ${hidden.fix}.`, + "every key in it is ignored, including `description`, `alwaysRun`, `model`, `paths` " + + `and \`effort\`. Fix: ${hidden.fix}.`, ]; } const warnings: string[] = []; diff --git a/src/config/schema.ts b/src/config/schema.ts index 4af1726..88c1b12 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -584,6 +584,23 @@ export const ScopeReviewConfigSchema = ReviewConfigSchema.omit({ }); export type RawScopeReviewConfig = z.infer; +/** The effort levels an agent may set. Each engine maps them (LLP 0006, "Agent Effort"). */ +export const AGENT_EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const; +export type AgentEffort = (typeof AGENT_EFFORT_LEVELS)[number]; + +/** + * The level a no-tools fallback pass runs at: the agent's own level, capped at `medium`. + * The fallback retries a timed-out pass under a short cap, so a deep level would likely + * time out again; sending no level instead would fall back to a provider default that can + * be higher than the agent's own `low`. + */ +// @ref LLP 0006#agent-effort [implements] — the no-tools fallback runs at min(level, medium) +export function fallbackEffort(level: AgentEffort): AgentEffort { + return AGENT_EFFORT_LEVELS.indexOf(level) <= AGENT_EFFORT_LEVELS.indexOf("medium") + ? level + : "medium"; +} + /** A single agent after prompt files are read and models are resolved. */ export interface LoadedAgent { id: string; @@ -604,6 +621,14 @@ export interface LoadedAgent { * or chunk that has at least one matching changed file. Absent means every change. */ paths?: string[]; + /** + * Frontmatter `effort`: how much reasoning the model spends on this agent's passes. + * The claude-code engine passes it as `--effort`; OpenCode passes it for OpenAI, Gemini 3 + * and later, and xAI models (opencodeEffortStyle). Absent leaves the level to the engine: + * the CLI default, or on OpenCode the model's default. On OpenCode, a variant set on a + * same-named agent in the developer's own OpenCode config wins over it. + */ + effort?: AgentEffort; /** * Frontmatter `mention`: GitHub logins or `org/team` slugs. When the agent asks for a * human review, the review comment mentions them. Absent means the agent mentions diff --git a/src/core/claude-code.ts b/src/core/claude-code.ts index 5d9fb73..ed4590a 100644 --- a/src/core/claude-code.ts +++ b/src/core/claude-code.ts @@ -3,7 +3,14 @@ import { tmpdir } from "node:os"; import path from "node:path"; -import type { LoadedConfig, McpServerConfig } from "../config/schema.js"; +import { fallbackEffort } from "../config/schema.js"; +import type { + AgentEffort, + AuthConfigEntry, + LoadedAgent, + LoadedConfig, + McpServerConfig, +} from "../config/schema.js"; import { checkAuthEntry } from "./auth.js"; import { pathInside, resolveOnPath, run } from "./exec.js"; import { assertMcpServerTokenEnvs, mcpGrantEnvironment, mcpServerGrants } from "./mcp-servers.js"; @@ -14,12 +21,15 @@ import { AgentTimeoutError, CLAUDE_CODE_ENGINE, CROSS_CUTTING_AGENT, + GOOGLE_THINKING_LEVELS, + OPENCODE_BUILTIN_AGENTS, + opencodeEffortStyle, STACK_VERIFIER_AGENT, VERIFIER_AGENT, withTransientRetry, } from "./opencode.js"; import type { OpencodeHandle, PromptResult, TokenUsage } from "./opencode.js"; -import { buildClaudeSessionExport } from "./session-archive.js"; +import { buildClaudeSessionExport, NON_REVIEWER_AGENTS } from "./session-archive.js"; import { RateLimitWatch } from "./throttle.js"; import { CLAUDE_RESEARCH_TOOLS } from "./research.js"; import type { ResearchMcpRuntime } from "./research.js"; @@ -45,6 +55,12 @@ export interface ClaudeCodeHandle extends OpencodeHandle { * the read-capable subset to the tree. */ tools: Record; + /** + * agent id → frontmatter `effort`, only for the reviewers that declare one + * (buildAgentEfforts). The fixed roles (cross-cutting, verifier, adjudicator, stack + * verifier, coordinator) have no entry and run at the CLI default. + */ + efforts?: ReadonlyMap; /** Default model for cross-cutting/verifier (config.agents[0].model). */ defaultModel: string; /** Absolute `claude` binary (PATH lookup). */ @@ -331,6 +347,8 @@ export function buildClaudeArgs(opts: { mcpServerTools?: readonly string[]; maxTurns?: number; jsonSchema?: Record; + /** `--effort` level. Absent passes no flag, so the CLI default applies. */ + effort?: AgentEffort; }): string[] { // Permission rules are gitignore-style with forward slashes; a Windows cwd // (`C:\Users\dev\repo`) must be normalized or every rule silently matches @@ -363,6 +381,8 @@ export function buildClaudeArgs(opts: { "--verbose", "--model", opts.model, + // @ref LLP 0006#agent-effort [implements] — the flag is passed only for an agent that declares a level + ...(opts.effort ? ["--effort", opts.effort] : []), "--append-system-prompt", opts.system, ...(opts.jsonSchema ? ["--json-schema", JSON.stringify(opts.jsonSchema)] : []), @@ -773,6 +793,181 @@ export function claudeTemperatureNote( : null; } +/** + * Ids the engine dispatches its fixed passes under (the same set the session archive + * uses). A reviewer file can share one (agents/verifier.md); its `effort` must not + * reach the built-in pass of that id. + */ +const FIXED_ROLE_IDS: ReadonlySet = NON_REVIEWER_AGENTS; + +/** + * agent id → frontmatter `effort`, for the reviewers that declare one. A reviewer whose + * id is also a fixed role's id gets no entry: passes are looked up by id, so its level + * would otherwise apply to the built-in pass as well. + */ +// @ref LLP 0006#agent-effort [implements] — the fixed roles always run at the CLI default +export function buildAgentEfforts(config: LoadedConfig): Map { + const efforts = new Map(); + for (const agent of config.agents) { + if (agent.effort && !FIXED_ROLE_IDS.has(agent.id)) { + efforts.set(agent.id, agent.effort); + } + } + return efforts; +} + +/** + * A one-time run note for an `effort` that has no effect. It states a fact about the + * setup, not about a pass, so it stays true when a later step (a blocking pre-check, the + * budget) skips the agent. The cases: the agent's model runs through OpenCode on a + * provider ecr passes no level to (`opencodeEffortStyle` is null); a Gemini 2.5 or older + * model, which takes a thinking budget (`google-budget`); a Google model with a level its + * OpenCode adapter does not take (`GOOGLE_THINKING_LEVELS`); an OpenCode-routed + * agent whose id is also an OpenCode built-in agent (`OPENCODE_BUILTIN_AGENTS`); an agent + * whose id is also a fixed role's id. Each agent is named once, with the full fix. `agents` is the run's selected reviewer list, after the `paths` + * filter and the router, so an agent either of them left out is never named. Returns null + * when every declared `effort` applies. + */ +export function agentEffortNote( + agents: readonly LoadedAgent[], + engineOf: Record, + auth: readonly AuthConfigEntry[], +): string | null { + const declared = agents.filter((agent) => agent.effort); + const takesNoLevel = (model: string): boolean => { + if (engineForModel(model) !== "opencode") { + return false; + } + const style = opencodeEffortStyle(model, auth); + return style === null || style === "google-budget"; + }; + const viaOpencode = declared + .filter( + (agent) => + !FIXED_ROLE_IDS.has(agent.id) && + !OPENCODE_BUILTIN_AGENTS.has(agent.id) && + engineOf[agent.id] === "opencode" && + opencodeEffortStyle(agent.model ?? "", auth) === null, + ) + .map((agent) => agent.id); + // A Google model whose level the pinned adapter rejects gets no level (opencodeEffortOptions). + const googleLevelNotTaken = declared + .filter( + (agent) => + !FIXED_ROLE_IDS.has(agent.id) && + !OPENCODE_BUILTIN_AGENTS.has(agent.id) && + engineOf[agent.id] === "opencode" && + opencodeEffortStyle(agent.model ?? "", auth) === "google" && + agent.effort !== undefined && + !GOOGLE_THINKING_LEVELS.has(agent.effort), + ) + .map((agent) => `${agent.id} (${agent.effort})`); + // Gemini 2.5 and older take a thinking budget, not a level (opencodeEffortStyle). + const googleBudget = declared + .filter( + (agent) => + !FIXED_ROLE_IDS.has(agent.id) && + !OPENCODE_BUILTIN_AGENTS.has(agent.id) && + engineOf[agent.id] === "opencode" && + opencodeEffortStyle(agent.model ?? "", auth) === "google-budget", + ) + .map((agent) => agent.id); + const fixedRole = declared + .filter((agent) => FIXED_ROLE_IDS.has(agent.id)) + .map((agent) => agent.id); + // buildOpencodeConfig gives an OpenCode built-in agent id no level (other sessions use it). + const opencodeBuiltin = declared + .filter( + (agent) => + !FIXED_ROLE_IDS.has(agent.id) && + OPENCODE_BUILTIN_AGENTS.has(agent.id) && + engineOf[agent.id] === "opencode", + ) + .map((agent) => agent.id); + // After a rename, the model still has to take a level; say so in the same note. + const builtinNoLevel = opencodeBuiltin.filter((id) => + takesNoLevel(declared.find((agent) => agent.id === id)?.model ?? ""), + ); + const builtinGoogleLevel = declared + .filter( + (agent) => + opencodeBuiltin.includes(agent.id) && + opencodeEffortStyle(agent.model ?? "", auth) === "google" && + agent.effort !== undefined && + !GOOGLE_THINKING_LEVELS.has(agent.effort), + ) + .map((agent) => agent.id); + const notes: string[] = []; + if (opencodeBuiltin.length > 0) { + notes.push( + `\`effort\` has no effect for ${opencodeBuiltin.join(", ")}: the id is also an OpenCode ` + + "built-in agent, which other sessions use. Fix: rename the agent file" + + (builtinNoLevel.length > 0 + ? `, and run ${builtinNoLevel.join(", ")} on a model that takes a level ` + + `(${EFFORT_PROVIDERS}; its \`model:\`, or \`REVIEWER_MODEL\` when that is set)` + : "") + + (builtinGoogleLevel.length > 0 + ? `, and give ${builtinGoogleLevel.join(", ")} one of ` + + `${[...GOOGLE_THINKING_LEVELS].join(", ")} (OpenCode's Google adapter takes no other)` + : ""), + ); + } + if (viaOpencode.length > 0) { + notes.push( + `\`effort\` has no effect for ${viaOpencode.join(", ")}: the model of each runs through ` + + `OpenCode on a provider ecr passes no level to (ecr passes one only for ${EFFORT_PROVIDERS})`, + ); + } + if (googleBudget.length > 0) { + notes.push( + `\`effort\` has no effect for ${googleBudget.join(", ")}: Gemini 2.5 and older models take a ` + + "thinking budget, not a level, so ecr sends none. Fix: use a Gemini 3 or later model with " + + "low, medium or high, or remove `effort`", + ); + } + if (googleLevelNotTaken.length > 0) { + notes.push( + `\`effort\` has no effect for ${googleLevelNotTaken.join(", ")}: OpenCode's Google adapter ` + + `takes only ${[...GOOGLE_THINKING_LEVELS].join(", ")}, so ecr sends no level and the model ` + + "runs at the model's default in OpenCode. Fix: use one of those levels", + ); + } + // The engine map's entry for a fixed-role id describes the built-in pass, so read the + // reviewer's own model: after a rename, a model that takes no level still ignores it. + const fixedRoleNoLevel = declared + .filter((agent) => FIXED_ROLE_IDS.has(agent.id) && takesNoLevel(agent.model ?? "")) + .map((agent) => agent.id); + // After a rename, a Google model still drops a level its adapter does not take. + const fixedRoleGoogleLevel = declared + .filter( + (agent) => + FIXED_ROLE_IDS.has(agent.id) && + opencodeEffortStyle(agent.model ?? "", auth) === "google" && + agent.effort !== undefined && + !GOOGLE_THINKING_LEVELS.has(agent.effort), + ) + .map((agent) => agent.id); + if (fixedRole.length > 0) { + notes.push( + `\`effort\` has no effect for ${fixedRole.join(", ")}: the id is also a built-in pass, which ` + + "runs at the default effort. Fix: rename the agent file" + + (fixedRoleNoLevel.length > 0 + ? `, and run ${fixedRoleNoLevel.join(", ")} on a model that takes a level ` + + `(${EFFORT_PROVIDERS}; its \`model:\`, or \`REVIEWER_MODEL\` when that is set)` + : "") + + (fixedRoleGoogleLevel.length > 0 + ? `, and give ${fixedRoleGoogleLevel.join(", ")} one of ` + + `${[...GOOGLE_THINKING_LEVELS].join(", ")} (OpenCode's Google adapter takes no other)` + : ""), + ); + } + return notes.length > 0 ? notes.join("; ") : null; +} + +/** The model families ecr passes an effort level to, for the run notes. */ +const EFFORT_PROVIDERS = + '`anthropic/…`, `openai/…` (or an `upstream: "openai"` alias), `google/…` or `google-vertex/…` (Gemini 3 and later), or `xai/…`'; + /** * Preserve actionable process diagnostics without copying arbitrary stderr into a * public Actions log. A non-empty stream may already contain model/tool content, so @@ -858,6 +1053,10 @@ export async function runClaudePrompt( }, CLAUDE_HEARTBEAT_MS) : undefined; heartbeat?.unref?.(); + // A Map lookup: an agent id such as `constructor` must not read an inherited value. + // The no-tools fallback (maxToolCalls 0) runs at the agent's level capped at `medium`. + const level = handle.efforts?.get(args.agent); + const effort = level && args.maxToolCalls === 0 ? fallbackEffort(level) : level; let result; try { result = await run( @@ -876,6 +1075,7 @@ export async function runClaudePrompt( mcpServerTools: [...mcpServerTools.keys()], maxTurns, jsonSchema: args.jsonSchema, + ...(effort ? { effort } : {}), }), { input: args.text, @@ -1289,6 +1489,7 @@ export async function startClaudeCode( // verifier never reads the disk (mirrors the coordinator's empty list). tools[STACK_VERIFIER_AGENT] = []; tools["coordinator"] = []; + const efforts = buildAgentEfforts(config); const defaultModel = config.agents[0]?.model ?? config.coordinator.model; const researchAgents = new Set(config.agents.map((agent) => agent.id)); researchAgents.add(CROSS_CUTTING_AGENT); @@ -1311,6 +1512,7 @@ export async function startClaudeCode( engine: CLAUDE_CODE_ENGINE, models, tools, + ...(efforts.size > 0 ? { efforts } : {}), defaultModel, cliPath, childEnv, diff --git a/src/core/opencode.ts b/src/core/opencode.ts index dbaa07f..7710f2a 100644 --- a/src/core/opencode.ts +++ b/src/core/opencode.ts @@ -5,12 +5,18 @@ import path from "node:path"; import { createOpencode } from "@opencode-ai/sdk"; -import type { LoadedConfig, McpServerConfig } from "../config/schema.js"; +import type { + AgentEffort, + AuthConfigEntry, + LoadedConfig, + McpServerConfig, +} from "../config/schema.js"; // Type-only: erased at compile time, so it creates NO runtime import cycle. The // Claude engine is reached at runtime via dynamic import() in the dispatch // branches below; claude-code.ts statically imports the shared helpers here. import type { ClaudeCodeHandle, Engine } from "./claude-code.js"; import type { SessionCapture } from "./session-archive.js"; +import { NON_REVIEWER_AGENTS } from "./session-archive.js"; import { pathInside, resolveOnPath } from "./exec.js"; import { RateLimitWatch } from "./throttle.js"; import { OPENCODE_RESEARCH_TOOLS, toolMap } from "./tools.js"; @@ -274,6 +280,101 @@ export const ADJUDICATOR_AGENT = "adjudicator"; // that structural, like the coordinator. export const STACK_VERIFIER_AGENT = "stack-verifier"; +/** + * How an OpenCode provider's SDK takes a reasoning level from an agent's config: + * OpenAI's Responses adapter and xAI's adapter read `reasoningEffort`, Google's reads + * `thinkingConfig.thinkingLevel` (Gemini 3 and later). `google-budget` marks Gemini 2.5 and + * older, which take a thinking budget instead; ecr sends them nothing. + */ +export type OpencodeEffortStyle = "openai" | "google" | "google-budget" | "xai"; + +/** + * The effort style for a model id, or null when ecr does not pass a level to that + * provider. Native `openai` gets the OpenAI style, Gemini models on native `google` and + * `google-vertex` the Google style, native `xai` (Grok) the xAI style. Other + * `google-vertex` models (Claude on Vertex) use another adapter, so they get null. An + * alias (an auth entry with `upstream`) follows the adapter `buildOpencodeConfig` creates + * for it: only `upstream: "openai"` gets `@ai-sdk/openai`, so only that alias takes a + * level. Meta, OpenAI-compatible and other providers get null. + */ +// @ref LLP 0006#agent-effort [implements] — OpenCode-routed effort, per provider adapter +export function opencodeEffortStyle( + model: string, + auth: readonly AuthConfigEntry[], +): OpencodeEffortStyle | null { + const slash = model.indexOf("/"); + if (slash <= 0) { + return null; + } + const provider = model.slice(0, slash); + const alias = auth.find((entry) => entry.provider === provider && entry.upstream); + if (alias) { + return alias.upstream === "openai" ? "openai" : null; + } + if (provider === "openai") { + return "openai"; + } + if (provider === "google" || provider === "google-vertex") { + // Only Gemini takes `thinkingConfig`: Vertex also serves Claude, on the Anthropic + // adapter. Gemini 2.5 and older take a thinking budget, not a level, so they get none. + const id = model.slice(slash + 1); + if (!id.startsWith("gemini-")) { + return null; + } + return /^gemini-[12](?:[.-]|$)/.test(id) ? "google-budget" : "google"; + } + if (provider === "xai") { + return "xai"; + } + return null; +} + +/** + * The levels the pinned OpenCode's Google adapter takes for `thinkingLevel`. With + * OpenCode 1.19.5, `xhigh` and `max` fail locally with an invalid-provider-options error + * and no request is sent (LLP 0006), so ecr sends no level for them. + */ +export const GOOGLE_THINKING_LEVELS: ReadonlySet = new Set(["low", "medium", "high"]); + +/** + * The agent-config keys that carry a reasoning level for an effort style, or null when + * the style's adapter does not take that level. OpenCode passes unknown agent keys to + * the provider as model options; observed with OpenCode 1.19.5 against a mock endpoint + * (LLP 0006): `reasoningEffort` becomes the Responses API's `reasoning.effort` (OpenAI) + * and, for xAI, Chat Completions' `reasoning_effort` or the Responses API's `reasoning.effort` + * (OpenCode picks the endpoint), and `thinkingConfig.thinkingLevel` + * replaces the `high` that OpenCode sends to Gemini 4 Neon. + */ +export function opencodeEffortOptions( + style: OpencodeEffortStyle, + effort: AgentEffort, +): Record | null { + if (style === "openai" || style === "xai") { + return { reasoningEffort: effort }; + } + if (style === "google-budget") { + return null; + } + return GOOGLE_THINKING_LEVELS.has(effort) ? { thinkingConfig: { thinkingLevel: effort } } : null; +} + +/** + * The agents OpenCode 1.19.5 defines itself (`app.agents()` with `native: true`, + * observed 2026-11-26). `compaction`, `summary` and `title` run for every session, so a + * reviewer that shares one of these ids must not give it a level (LLP 0006). Re-check when + * the OpenCode pins move. + */ +// @ref LLP 0006#agent-effort [implements] — no level on OpenCode's own agent ids, which other sessions use +export const OPENCODE_BUILTIN_AGENTS: ReadonlySet = new Set([ + "build", + "compaction", + "explore", + "general", + "plan", + "summary", + "title", +]); + /** Build the inline OpenCode config (agents + coordinator) from a repo config. */ export function buildOpencodeConfig( config: LoadedConfig, @@ -282,11 +383,27 @@ export function buildOpencodeConfig( ): Record { const agent: Record = {}; for (const reviewer of config.agents) { + // No level for an id the engine or OpenCode also uses: ecr's fixed roles replace the + // entry after this loop, and an OpenCode built-in agent (compaction, title, …) also + // runs for other sessions, so a level there would reach them. + const effortStyle = + reviewer.effort && + !NON_REVIEWER_AGENTS.has(reviewer.id) && + !OPENCODE_BUILTIN_AGENTS.has(reviewer.id) + ? opencodeEffortStyle(reviewer.model, config.auth) + : null; + const effortOptions = + reviewer.effort && effortStyle ? opencodeEffortOptions(effortStyle, reviewer.effort) : null; agent[reviewer.id] = { description: `${reviewer.id} reviewer`, mode: "all", model: reviewer.model, temperature: reviewer.temperature, + // Only reviewers: the fixed roles below are written after this loop, so a reviewer + // that shares a fixed role's id cannot give that pass its level. A model variant + // set on a same-named agent in the developer's own OpenCode config still applies + // after these options and wins (LLP 0006). + ...effortOptions, prompt: `You are the ${reviewer.id} code reviewer. Follow the user message exactly and return only the requested JSON.`, tools: { ...reviewer.tools, diff --git a/src/core/review.ts b/src/core/review.ts index 8a103fc..ba44e10 100644 --- a/src/core/review.ts +++ b/src/core/review.ts @@ -1,7 +1,7 @@ // @ref LLP 0002#pipeline-stages [implements] — the mode-agnostic pipeline core owning budgets, coverage, and logging import path from "node:path"; -import type { LoadedAgent, LoadedConfig } from "../config/schema.js"; +import type { AuthConfigEntry, LoadedAgent, LoadedConfig } from "../config/schema.js"; import type { PreparedReadRoot, ReviewSource, @@ -32,13 +32,15 @@ import { import type { OpencodeHandle, TokenUsage } from "./opencode.js"; import type { SessionCapture } from "./session-archive.js"; import { + agentEffortNote, buildEngineMap, claudeTemperatureNote, claudeTokenCredential, startClaudeCode, } from "./claude-code.js"; -import type { ClaudeCodeHandle } from "./claude-code.js"; +import type { ClaudeCodeHandle, Engine } from "./claude-code.js"; import { routeAgents } from "./router.js"; +import type { RouteResult } from "./router.js"; import { changedPaths, formatSkippedAgents, @@ -697,22 +699,20 @@ export async function runReview( // Resolve which agents run: an explicit list wins; otherwise route (LLM picks // relevant agents + always-run) when asked, else all. Routing chooses only among // the agents the `paths` filter kept. - let selectedAgents = pathsSelection.agents; - if (!explicitAgents && options.route) { - progress("Routing: selecting relevant agents…"); - const routed = await routeAgents(handle, pathsSelection.agents, workspace.files, (line) => - progress(formatAgentActivity("router", "router", line)), - ); - selectedAgents = routed.agents; - progress( - routed.routed - ? `Router selected: ${selectedAgents.map((a) => a.id).join(", ")}` - : "Router unavailable; running all agents.", - ); - } - const notRouted = pathsSelection.agents - .filter((agent) => !selectedAgents.includes(agent)) - .map((agent) => agent.id); + const { selectedAgents, notRouted } = await selectReviewers({ + candidates: pathsSelection.agents, + ...(!explicitAgents && options.route + ? { + route: () => + routeAgents(handle, pathsSelection.agents, workspace.files, (line) => + progress(formatAgentActivity("router", "router", line)), + ), + } + : {}), + engineOf, + auth: config.auth, + progress, + }); // Split the diff into focused chunks so each reviewer call sees a small file // set (better recall than one giant blob), and run all agent×chunk calls @@ -2360,6 +2360,45 @@ export function decisionAfterGrounding( : previous; } +/** + * Resolve which reviewers run, then report an `effort` that has no effect on them. + * `candidates` are the agents the `paths` filter kept; `route`, when given, picks among + * them (the LLM router in a review, a stand-in in tests). Exported for tests. + */ +export async function selectReviewers(args: { + candidates: LoadedAgent[]; + route?: () => Promise; + engineOf: Record; + /** The run's credentials: a provider alias takes its upstream's effort support. */ + auth: readonly AuthConfigEntry[]; + progress: (line: string) => void; +}): Promise<{ selectedAgents: LoadedAgent[]; notRouted: string[] }> { + let selectedAgents = args.candidates; + if (args.route) { + args.progress("Routing: selecting relevant agents…"); + const routed = await args.route(); + selectedAgents = routed.agents; + args.progress( + routed.routed + ? `Router selected: ${selectedAgents.map((a) => a.id).join(", ")}` + : "Router unavailable; running all agents.", + ); + } + const notRouted = args.candidates + .filter((agent) => !selectedAgents.includes(agent)) + .map((agent) => agent.id); + + // `effort` reaches the `claude` CLI and OpenCode's OpenAI and Google adapters, and never + // a fixed pass. Say so once for a selected reviewer whose level has no effect, so the + // setting does not fail silently. + // @ref LLP 0006#agent-effort [implements] — built from the selected reviewer list, after the paths filter and the router, so an agent either of them left out is never named; a later pre-check or budget limit can still skip a named one + const effortNote = agentEffortNote(selectedAgents, args.engineOf, args.auth); + if (effortNote) { + args.progress(`Note: ${effortNote}`); + } + return { selectedAgents, notRouted }; +} + /** * The coordinator writes its summary before findings are verified/suppressed, so a * post-coordination drop can leave the summary referencing issues no longer shown. diff --git a/templates/config.jsonc b/templates/config.jsonc index e0a895a..60d6d95 100644 --- a/templates/config.jsonc +++ b/templates/config.jsonc @@ -14,6 +14,10 @@ // e.g. `---\nmodel: anthropic/claude-opus-5-5\n---`. `paths: ["packages/ios/**"]` // there limits an agent to changes that touch those globs, and `mention: [octocat]` // names the people the review mentions when that agent asks for a human review. + // `effort: high` (low, medium, high, xhigh or max) sets how much an agent reasons on + // `anthropic/…`, `openai/…` (or an `upstream: "openai"` alias), Gemini 3 and later + // (low, medium or high only) and `xai/…` models; other models get no level. A model + // can ignore a level, or its provider can reject it. README: "effort". // @ref LLP 0009#config-and-prompt-templates [implements] — suggestions off by default, not a schema limit "policy": {