Skip to content

Commit f5e10cc

Browse files
authored
fix: plan-mode refusals on altimate-default + warning false-positive (#887) (#888)
* fix: plan-agent tool-use — mandate exploration + reword misleading warning When the plan agent runs on a tool-capable but compliant model (e.g. GPT-5.5 via `altimate-default`), it often emits a plan from prompt context alone without ever reading the repo. The existing safety net in `processor.ts` catches this and surfaces a warning suggesting the user "switch to a model with stronger tool-use via /model". That diagnosis is misleading — the model IS tool-capable; it's a prompt-engineering issue, not a capability issue. This patch addresses both halves of the problem: - **`plan.txt`**: adds a `## Investigate before drafting (REQUIRED)` section that explicitly mandates at least one read-only tool call (`read`/`grep`/`glob`/`list`/`explore`/read-only `bash`) before any plan content. Stronger Claude models already infer this; weaker compliant models need it spelled out. Includes an explicit escape hatch for the trivial-task case so the rule doesn't fire spuriously. - **`processor.ts`**: rewords the synthetic warning to describe the observed behavior (`produced a plan without first reading any files`) and offer two concrete remedies — reply asking it to explore first, or `/model` to a more eager-to-investigate tier (Claude Sonnet/Opus). No longer blames "tool-use capability." - **`plan-reminder-anthropic.txt`**: deleted. The file was never imported anywhere in the codebase — it was an upstream OpenCode artifact that survived the rename in commit `a4eba2e6e` ("tweak: plan prompt"). Removing dead config. - Regression test in `plan-layer-e2e.test.ts` locks the explore-first contract into the prompt so a future cleanup can't silently delete it. All 160 affected tests pass; typecheck clean. * fix: plan-agent tool-use — warning copy covers refusal case too Field test surfaced a second failure mode the prior warning misframed: when the planner refuses the request outright ("I'm sorry, but I cannot assist…" — observed on `altimate-default` for a benign "add a YOLO-mode toggle button" request), the trip-wire fires (plan + finish=stop + zero tools) but the previous copy told the user the model "produced a plan without first reading any files." It did not — it refused. Reword the warning to be accurate for **both** failure modes without pattern-matching refusal text (brittle, locale-specific): - describe the observed symptom only ("stopped without calling any tools") - enumerate three common causes (prompt-context plan / content-policy refusal / under-specified request) - offer three concrete recoveries (ask to investigate, rephrase, /model) The trip-wire condition is unchanged; only the synthetic text the user sees is updated. Telemetry event shape is unchanged. This builds on d21f9b1 and supersedes the warning copy from that commit. * fix: altimate-backend models hit Claude-fallback prompt that triggered GPT-5.x refusals Root cause of the plan-mode refusals on `altimate-backend/altimate-default`: the system-prompt router in `session/system.ts` selects a base prompt by string-matching `model.api.id`. The gateway's api.id is the opaque alias `altimate-default` (kept stable for backward compatibility — users persist it in `model.json` favorites/recents), which matches none of the patterns (`gpt-5`, `gpt-`, `gemini-`, `claude`, `trinity`), so it falls through to `PROMPT_ANTHROPIC_WITHOUT_TODO` (`qwen.txt`). `qwen.txt` begins with two hard "MUST refuse if borderline/malicious" Claude-style directives. The upstream gateway model is GPT-5.x (an OpenAI-trained model), and when those directives stack with plan.txt's "STRICTLY FORBIDDEN: ANY modifications. ZERO exceptions." language, the combination is enough to push GPT-5.x into refusing benign developer requests (confirmed repro: "plan a feature to add a button called verify output in the UI of altimate-code" → "I'm sorry, but I cannot assist with that request."). Fix: route altimate-backend models by `model.family` (which the provider definition explicitly pins to `"openai"` for `altimate-default` at `provider.ts:1291`) before the api.id string-match fallthrough. The gateway-routed GPT-5.x model now gets `codex_header.txt` (its native prompt) which contains zero refusal language. Touches: - `packages/opencode/src/session/system.ts`: family-based routing for altimate-backend; falls through to existing logic otherwise. - `packages/opencode/test/session/system.test.ts`: regression tests locking the routing contract for the three relevant cases (altimate openai, altimate anthropic, non-altimate openai). This is the actual fix for #887 / AI-6957 — supersedes the warning-copy and plan.txt changes from d21f9b1 / 6bbcfbf as the *user-visible* behavior change. Those earlier commits remain correct: stronger exploration mandate in plan.txt and accurate warning copy are still improvements, just not the load-bearing fix. Typecheck clean. 620 tests pass. * fix: hoist <system-reminder> to system role for non-Anthropic models + warning false-positive Two related bugs the trace finally revealed, after the qwen.txt theory in b07da4e didn't actually fix the refusal in production: 1. **Root cause of GPT-5.x refusals**: prompt.ts:2049 attaches PROMPT_PLAN (wrapped in `<system-reminder>...</system-reminder>` tags) as a text part on the latest user message. Claude is trained to recognize that tag as authoritative system-level instructions even when delivered in a user-role message. OpenAI / Google / etc. models are NOT — they see a user message containing a `<system-reminder>` block with aggressive constraint language (STRICTLY FORBIDDEN / ZERO exceptions / ABSOLUTE CONSTRAINT / MUST) and pattern-match it as a prompt-injection attempt. GPT-5.x via `altimate-backend/altimate-default` reliably returned "I'm sorry, but I cannot assist with that request." for benign developer requests like "plan a feature to add a button…". Confirmed by reading the actual LLM payload via temporary debug instrumentation in `llm.ts` (since removed). Fix in `llm.ts`: for non-Anthropic-like models, walk `input.messages` and extract any `<system-reminder>`-wrapped text parts from user-role messages, then append them to the system array so they arrive as proper `role:"system"` messages. User messages that become empty after extraction are dropped. Anthropic-like models keep the existing behavior. Detection of Anthropic-like uses providerID + family + api.npm + the existing api.id substring patterns, matching the heuristics already used in `provider/transform.ts:284-295` for cache-control handling. 2. **Counter scope bug in plan-no-tool warning**: `sessionToolCallsMade` in `processor.ts:57` was claimed (comment line 207) to be session- scoped, but `SessionProcessor.create()` is called per-step by `loop()` in `prompt.ts:485`, so the counter resets each step. A multi-step plan session (read → grep → read → … → final text) false-positives on the last text-only step. The warning fires *after* the agent has successfully explored the codebase and produced a plan — confusing the user into thinking the session failed. Fix: at warning-check time, also scan `streamInput.messages` for any prior assistant tool-call content. The session has used tools iff either the per-step counter is non-zero OR the history contains a tool-call. Regression test added in `processor.test.ts`. The earlier `system.ts` family-based routing (commit b07da4e) stays. It was based on a wrong root-cause theory, but the change itself is correct: a model with `family: "openai"` should not fall through to qwen.txt (an Anthropic-style fallback). Worth keeping as defense in depth even though it wasn't the load-bearing fix. Touches: - `packages/opencode/src/session/llm.ts`: system-reminder hoist. - `packages/opencode/src/session/processor.ts`: warning false-positive fix + comment block explaining the per-step scoping. - `packages/opencode/test/session/processor.test.ts`: regression test for the warning false-positive. Typecheck clean. 124 affected tests pass. This is the actual fix for #887 / AI-6957. * fix: address PR #888 bot review — trust provenance, biome lint, safe defaults Triage of automated review feedback on #888 — addresses the genuine findings, skips the rest with reasons. ## Addressed **Trust provenance for `<system-reminder>` hoisting** (CodeRabbit `llm.ts:106`, cubic `llm.ts:94` — both P1/Major) Moves the hoist from `llm.ts` to `prompt.ts`, where the `synthetic` flag on `MessageV2.TextPart` is still available. The hoist now qualifies a part only if `synthetic === true` AND text begins with `<system-reminder>` — raw user text starting with the same characters is left in place and never gains system-role priority. The synthetic flag is the trust boundary: it is only set by `insertReminders` when altimate-code itself injects PROMPT_PLAN / BUILD_SWITCH. The `isAnthropicLikeModel` helper is colocated with the new hoist. **Safe default for unknown families on altimate-backend** (cubic `system.ts:46` — P2) `SystemPrompt.provider` previously fell through to `PROMPT_ANTHROPIC_WITHOUT_TODO` when an altimate-backend model had a family value not in the explicit list — recreating the original routing problem the moment a new family value appears in config. Now defaults unknown families to `PROMPT_CODEX` because the gateway is registered as `@ai-sdk/openai-compatible`. Regression test added. **Case-insensitive family lookup** (cubic `system.ts:45` — P2) `family` is a free-form string in the model schema. Now compared via `?.toLowerCase()`. Regression test covers `Anthropic` / `ANTHROPIC` / `anthropic` parity. **Biome `noSwitchDeclarations` lint** (CodeRabbit `processor.ts:367` — Minor) Wraps the `finish-step` case body in a block so `sessionHasPriorToolCalls` can't leak. **Strengthened anthropic-family regression test** (CodeRabbit `system.test.ts:62` — Minor) Asserts exact equality with a baseline anthropic routing call instead of two loose negative regex checks. **Removed conversation artifact** Test comment referenced "the 2026-06-04 comment claimed" — date was a leftover from the investigation timeline. Reworded to describe the behavior directly without anchoring to today's date. **Reframed `system.ts` routing comment** Earlier wording attributed the GPT-5.x refusal fix to this routing change. The actual fix is the user-message `<system-reminder>` hoist in `prompt.ts`. Comment now correctly frames this as defense in depth. ## Skipped (with reasons) - **dev-punia-altimate `llm.ts:78`** — "may incorrectly drop user messages that contain both a `<system-reminder>` part and other valid content." Misreads the code. The filter only drops messages where `content.length === 0` AFTER extraction; messages with both a reminder and other content keep their other content. Not applicable to the new prompt.ts hoist either, which operates on parts not whole messages. - **dev-punia-altimate `processor.ts:355`** — "tool calls in earlier steps may not be preserved in current `streamInput.messages`." Not the case: `message-v2.ts` `toModelMessages` (lines 707-769) emits every completed tool call as a `tool-${name}`-typed part on the assistant message, which AI SDK's `convertToModelMessages` lowers to `tool-call` content. Verified by reading the conversion path. - **dev-punia-altimate `llm.ts:64`** — "`altimate_change` marker is not permitted in CLAUDE.md, use `// NOTE: altimate`." Incorrect — the `// altimate_change start/end` convention is used throughout the codebase (grep finds hundreds of occurrences across packages/ opencode/src). Matching existing project style. Typecheck clean. 605 of 612 session tests pass (7 unrelated skips). * fix: tighten hoist trust boundary — `insertReminders` returns explicit candidates PR #888 review surfaced a real prompt-injection vector that the previous `synthetic + prefix` trust check could not close. The `MessageV2.TextPart.synthetic` flag is set by *several* code paths in `session/prompt.ts`, not just by reminder injection. In particular, the file/resource expansion paths at lines ~1729/1751/1801 attach *user-supplied content* (MCP resource bodies, `data:` URL decoded text, file attachments) as text parts with `synthetic: true`. A malicious file or resource whose body began with `<system-reminder>` would therefore have been hoisted into the system role on non-Anthropic models — exactly the privilege escalation the prior fix was meant to prevent. Caught by both CodeRabbit (PR #888 thread, `prompt.ts:2082`) and cubic (`prompt.ts:2078`). This commit narrows the trust boundary the way the reviewers suggested: `insertReminders` now returns the explicit list of parts it appended, and the loop hoists *only* those. `synthetic + prefix` inference is gone. - `insertReminders` return shape: `Promise<{ messages, trustedReminderParts }>`. Each `userMessage.parts.push(...)` site also pushes the same part into `trustedReminderParts` so the caller has the candidates without having to re-derive them. - `hoistSyntheticReminders` helper removed. The loop iterates `reminderResult.trustedReminderParts` directly: pushes the text into the system array, marks the part `ignored = true` so `toModelMessages` skips it in the user message. - `isAnthropicLikeModel` retained (still the gate for whether to hoist or leave reminders in-place). - Two regression tests added in `plan-layer-e2e.test.ts` that re-read `prompt.ts` to enforce the contract: the hoist must consume `trustedReminderParts` and must not re-introduce a `hoistSyntheticReminders`-style scan. Also removes the diagnostic dump from `llm.ts` (added in an earlier WIP for #888 investigation, not for shipping). The dump path under `~/.local/share/altimate-code/log/plan-debug/` is no longer written. Typecheck clean. 128 affected tests pass. * fix: J1 + J2 from PR #888 multi-LLM review J1 — exact family-string match misses real gateway values `system.ts` (and `prompt.ts:isAnthropicLikeModel`) compared `model.family` exactly against `"anthropic"` / `"gemini"`. But the model registry (`models-api.json`) uses *specific* family values like `claude-sonnet`, `claude-haiku`, `gemini-pro`, `gemini-flash`, `gpt-codex`, etc. — never the coarse literals. Any config-added Claude or Gemini model on the altimate-backend gateway therefore silently fell through to `PROMPT_CODEX` — recreating the GH #887 misrouting class this PR was meant to fix. Latent today because the only statically-registered altimate-backend model is `altimate-default` with `family: "openai"` (coarse). Fix: shared `familyVendor(family)` helper in `src/provider/family.ts` that maps `claude` / `claude-*` / `anthropic` → `"anthropic"`, `gemini` / `gemini-*` → `"gemini"`, `openai` / `openai-compatible` / `gpt` / `gpt-*` → `"openai"`. Used by both `SystemPrompt.provider` (altimate-backend block) and `isAnthropicLikeModel`. `isAnthropicLikeModel` also tightens the api.id substring matches (lowercased; `claude-` anchored to the last URL segment so `foo-claude-bench` doesn't false-match; `anthropic-`/`anthropic/` anchored to the path). J2 — experimental plan-mode reminders replay as user-role `<system-reminder>` on turn 2+ Under `OPENCODE_EXPERIMENTAL_PLAN_MODE=true`, `insertReminders` calls `Session.updatePart(...)` to persist the entering-plan-mode and build-switch reminder parts. The persisted row was written *without* `ignored: true`. The caller mutated `part.ignored = true` only on the in-memory copy, so on the next turn the DB-reloaded part had `ignored: undefined`, slipped past the `!part.ignored` filter in `toModelMessages`, and re-entered the user-role payload as `<system-reminder>...</system-reminder>` — re-triggering the GPT-5.x refusal class this PR fixes. Bug was flag-gated so the default path was unaffected, but the PR ships tests pinned to the experimental branches so it shipped the bug latent under the flag. Fix: push the hoist decision *into* `insertReminders`. The function now takes `model`, computes `nonAnthropic = !isAnthropicLikeModel(...)` once, and stamps `ignored: true` onto every trusted reminder at insertion time — including the `Session.updatePart` payloads, so the persisted row carries the flag across turns. Caller in `loop()` no longer mutates `part.ignored`; the contract is now owned by `insertReminders`. The hoist branch in `loop()` reduces to a simple `.map(p => p.text)` over `trustedReminderParts`. Tests - New: `test/provider/family.test.ts` table-drives `familyVendor` against every coarse-vs-specific case (claude/claude-haiku/ claude-opus/claude-sonnet/gemini/gemini-pro/gemini-flash/gpt/ gpt-codex), case-insensitivity, and the unknown→undefined contract. - `test/session/plan-layer-e2e.test.ts`: regression guards that (a) `system.ts` and `prompt.ts:isAnthropicLikeModel` both consume `familyVendor` and no exact `family === "anthropic"` shape lingers in the altimate-backend block; (b) `insertReminders` takes `model` and stamps `nonAnthropic ? { ignored: true } : {}` onto persisted reminder writes; (c) the caller no longer mutates `part.ignored`. 154 affected tests pass. Typecheck clean. Addresses #888 review J1, J2, and N1 (case-sensitivity / over-broad api.id substring) and N2 in spirit (`isAnthropicLikeModel` now has its classifier under direct test via `familyVendor`). --------- Co-authored-by: Haider <[email protected]>
1 parent cdf89a6 commit f5e10cc

10 files changed

Lines changed: 425 additions & 84 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// altimate_change start — shared vendor classifier for `model.family` values.
2+
//
3+
// `model.family` is a free-form string in the Model schema; the model registry
4+
// (`packages/opencode/test/tool/fixtures/models-api.json`) uses *specific*
5+
// values like `claude-sonnet`, `claude-haiku`, `gemini-pro`, `gemini-flash`,
6+
// `gpt-codex`, etc. — never the coarse `anthropic`/`gemini`/`openai` literals.
7+
// Routing code that exact-matches against the coarse names silently misses
8+
// real models, recreating the GH #887 misrouting class on any altimate-backend
9+
// gateway path that exposes Claude or Gemini models. Use this helper to map a
10+
// specific family value to its vendor bucket.
11+
//
12+
// Reviewer-driven addition (PR #888 review thread, J1 from the multi-LLM
13+
// panel). Keep this the single source of truth so the prompt-routing and the
14+
// hoist-decision both interpret family the same way.
15+
16+
export type Vendor = "anthropic" | "gemini" | "openai"
17+
18+
export function familyVendor(family: string | undefined): Vendor | undefined {
19+
if (!family) return undefined
20+
const f = family.toLowerCase()
21+
if (f === "anthropic" || f === "claude" || f.startsWith("claude-")) return "anthropic"
22+
if (f === "gemini" || f.startsWith("gemini-")) return "gemini"
23+
if (f === "openai" || f === "openai-compatible" || f === "gpt" || f.startsWith("gpt-")) return "openai"
24+
return undefined
25+
}
26+
// altimate_change end

‎packages/opencode/src/session/processor.ts‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ export namespace SessionProcessor {
303303
})
304304
break
305305

306-
case "finish-step":
306+
case "finish-step": {
307307
const usage = Session.getUsage({
308308
model: input.model,
309309
usage: value.usage,
@@ -348,10 +348,27 @@ export namespace SessionProcessor {
348348
// Users read the text, see no progress, and abandon. Surface a
349349
// warning + telemetry so the pattern is measurable and the user
350350
// knows to try a different model.
351+
//
352+
// sessionToolCallsMade tracks tool calls in the CURRENT step only
353+
// — SessionProcessor.create() is called per-step by loop() (see
354+
// prompt.ts), so the closure variable resets each step. A multi-
355+
// step plan-mode session (read → grep → read → … → final text)
356+
// would then false-positive on the final text-only step. Also
357+
// scan streamInput.messages for any prior assistant tool-call
358+
// content; if found, the session has used tools and the warning
359+
// should be suppressed.
360+
const sessionHasPriorToolCalls =
361+
sessionToolCallsMade > 0 ||
362+
streamInput.messages.some(
363+
(m) =>
364+
m.role === "assistant" &&
365+
Array.isArray(m.content) &&
366+
m.content.some((p) => p.type === "tool-call"),
367+
)
351368
if (
352369
input.assistantMessage.agent === "plan" &&
353370
value.finishReason === "stop" &&
354-
sessionToolCallsMade === 0 &&
371+
!sessionHasPriorToolCalls &&
355372
!planNoToolWarningEmitted
356373
) {
357374
planNoToolWarningEmitted = true
@@ -381,9 +398,13 @@ export namespace SessionProcessor {
381398
type: "text",
382399
synthetic: true,
383400
text:
384-
`⚠️ altimate-code: the \`plan\` agent is running on \`${input.model.providerID}/${input.model.id}\`, ` +
385-
`which returned text without calling any tools. If you expected the plan agent to explore the ` +
386-
`codebase, try switching to a model with stronger tool-use via \`/model\`.`,
401+
`⚠️ altimate-code: the \`plan\` agent on \`${input.model.providerID}/${input.model.id}\` ` +
402+
`stopped without calling any tools — it neither read, searched, nor explored the codebase. ` +
403+
`Common causes: (a) the model wrote a plan from prompt context alone, (b) the model declined ` +
404+
`to engage with the request (content-policy refusal), or (c) the request was too thin to act on. ` +
405+
`To recover, try one of: reply asking it to investigate first (\`read\`/\`grep\`/\`glob\`/\`explore\`); ` +
406+
`rephrase the request more concretely; or \`/model\` to a tier that's more eager to explore ` +
407+
`(e.g. Claude Sonnet/Opus).`,
387408
time: { start: Date.now(), end: Date.now() },
388409
})
389410
}
@@ -424,6 +445,7 @@ export namespace SessionProcessor {
424445
needsCompaction = true
425446
}
426447
break
448+
}
427449

428450
case "text-start":
429451
currentText = {

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 83 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ import { Session } from "."
1111
import { Agent } from "../agent/agent"
1212
import { Provider } from "../provider/provider"
1313
import { ModelID, ProviderID } from "../provider/schema"
14+
// altimate_change start — shared family→vendor classifier (#888 J1)
15+
import { familyVendor } from "../provider/family"
16+
// altimate_change end
1417
import { type Tool as AITool, tool, jsonSchema, type ToolCallOptions, asSchema } from "ai"
1518
import { SessionCompaction } from "./compaction"
1619
import { Instance } from "../project/instance"
@@ -688,11 +691,24 @@ export namespace SessionPrompt {
688691
const agent = await Agent.get(lastUser.agent)
689692
const maxSteps = agent.steps ?? Infinity
690693
const isLastStep = step >= maxSteps
691-
msgs = await insertReminders({
694+
// altimate_change start — insertReminders returns the trusted reminder parts
695+
// it appended. The function now also pre-applies `ignored: true` to those
696+
// parts (and to the persisted rows under experimental plan mode) for
697+
// non-Anthropic-like models, so `toModelMessages` skips them on every turn
698+
// — not just this one (#888 J2). The returned-parts list is the trust
699+
// boundary; we never infer trust from the `synthetic` flag (other code
700+
// paths set it on user-derived file/resource expansions). See #887/#888.
701+
const reminderResult = await insertReminders({
692702
messages: msgs,
693703
agent,
694704
session,
705+
model,
695706
})
707+
msgs = reminderResult.messages
708+
const hoistedReminders = isAnthropicLikeModel(model)
709+
? []
710+
: reminderResult.trustedReminderParts.map((p) => p.text)
711+
// altimate_change end
696712

697713
// altimate_change start — plan refinement detection and telemetry
698714
if (agent.name === "plan") {
@@ -968,6 +984,7 @@ export namespace SessionPrompt {
968984
...(skills ? [skills] : []),
969985
...(knowledgeInjection ? [knowledgeInjection] : []),
970986
...(await InstructionPrompt.system()),
987+
...hoistedReminders,
971988
]
972989
const format = lastUser.format ?? { type: "text" }
973990
if (format.type === "json_schema") {
@@ -2039,34 +2056,84 @@ export namespace SessionPrompt {
20392056
}
20402057
}
20412058

2042-
async function insertReminders(input: { messages: MessageV2.WithParts[]; agent: Agent.Info; session: Session.Info }) {
2059+
// altimate_change start — model-family helper used by the trust-aware hoist below.
2060+
// Uses `familyVendor` so specific family values (`claude-sonnet`, `claude-haiku`,
2061+
// `gemini-pro`, etc.) classify correctly — an exact `family === "anthropic"`
2062+
// check would miss the gateway-emitted specific names (#888 J1). The api.id
2063+
// checks are lowercased and tightened to a `claude-` / `anthropic-` /
2064+
// `anthropic/...` shape so a model named `foo-claude-bench` doesn't false-match.
2065+
function isAnthropicLikeModel(model: Provider.Model): boolean {
2066+
if (model.providerID === "anthropic") return true
2067+
if (model.providerID === "google-vertex-anthropic") return true
2068+
if (familyVendor(model.family) === "anthropic") return true
2069+
if (model.api.npm === "@ai-sdk/anthropic") return true
2070+
const apiId = model.api.id.toLowerCase()
2071+
const lastSeg = apiId.split("/").pop() ?? apiId
2072+
if (/^claude[-_.]/.test(lastSeg)) return true
2073+
if (/^anthropic[-_/]/.test(apiId)) return true
2074+
return false
2075+
}
2076+
// altimate_change end
2077+
2078+
// altimate_change start — return the trusted reminder parts insertReminders just appended
2079+
// so the caller can hoist them into the system prompt on non-Anthropic models.
2080+
// The returned-parts contract is the trust boundary: only parts that *this function*
2081+
// creates are eligible for promotion. The schema-wide `synthetic` flag is set by other
2082+
// code paths too (file/resource expansions at lines ~1729/1751/1801 attach
2083+
// file content as synthetic text), so it is not safe to infer trust from `synthetic`
2084+
// alone. See #888 review feedback.
2085+
type InsertRemindersResult = { messages: MessageV2.WithParts[]; trustedReminderParts: MessageV2.TextPart[] }
2086+
async function insertReminders(input: {
2087+
messages: MessageV2.WithParts[]
2088+
agent: Agent.Info
2089+
session: Session.Info
2090+
// altimate_change start — used to bake `ignored` into the persisted experimental
2091+
// plan-mode reminders so they don't replay as user-role `<system-reminder>` on
2092+
// turn 2+ on non-Anthropic models (#888 J2).
2093+
model: Provider.Model
2094+
// altimate_change end
2095+
}): Promise<InsertRemindersResult> {
2096+
const trustedReminderParts: MessageV2.TextPart[] = []
2097+
// altimate_change start — pre-compute the hoist decision once so it can be
2098+
// applied at insertion time (including to persisted rows). For non-Anthropic
2099+
// models, every trusted reminder is marked `ignored: true` immediately so
2100+
// `toModelMessages` will skip it (the caller no longer needs to mutate the
2101+
// flag, and DB-persisted rows survive the contract across turns).
2102+
const nonAnthropic = !isAnthropicLikeModel(input.model)
2103+
// altimate_change end
20432104
const userMessage = input.messages.findLast((msg) => msg.info.role === "user")
2044-
if (!userMessage) return input.messages
2105+
if (!userMessage) return { messages: input.messages, trustedReminderParts }
20452106

20462107
// Original logic when experimental plan mode is disabled
20472108
if (!Flag.OPENCODE_EXPERIMENTAL_PLAN_MODE) {
20482109
if (input.agent.name === "plan") {
2049-
userMessage.parts.push({
2110+
const part: MessageV2.TextPart = {
20502111
id: PartID.ascending(),
20512112
messageID: userMessage.info.id,
20522113
sessionID: userMessage.info.sessionID,
20532114
type: "text",
20542115
text: PROMPT_PLAN,
20552116
synthetic: true,
2056-
})
2117+
...(nonAnthropic ? { ignored: true } : {}),
2118+
}
2119+
userMessage.parts.push(part)
2120+
trustedReminderParts.push(part)
20572121
}
20582122
const wasPlan = input.messages.some((msg) => msg.info.role === "assistant" && msg.info.agent === "plan")
20592123
if (wasPlan && input.agent.name === "builder") {
2060-
userMessage.parts.push({
2124+
const part: MessageV2.TextPart = {
20612125
id: PartID.ascending(),
20622126
messageID: userMessage.info.id,
20632127
sessionID: userMessage.info.sessionID,
20642128
type: "text",
20652129
text: BUILD_SWITCH,
20662130
synthetic: true,
2067-
})
2131+
...(nonAnthropic ? { ignored: true } : {}),
2132+
}
2133+
userMessage.parts.push(part)
2134+
trustedReminderParts.push(part)
20682135
}
2069-
return input.messages
2136+
return { messages: input.messages, trustedReminderParts }
20702137
}
20712138

20722139
// New plan mode logic when flag is enabled
@@ -2085,10 +2152,12 @@ export namespace SessionPrompt {
20852152
text:
20862153
BUILD_SWITCH + "\n\n" + `A plan file exists at ${plan}. You should execute on the plan defined within it`,
20872154
synthetic: true,
2155+
...(nonAnthropic ? { ignored: true } : {}),
20882156
})
20892157
userMessage.parts.push(part)
2158+
trustedReminderParts.push(part as MessageV2.TextPart)
20902159
}
2091-
return input.messages
2160+
return { messages: input.messages, trustedReminderParts }
20922161
}
20932162

20942163
// Entering plan mode
@@ -2188,12 +2257,15 @@ This is critical - your turn should only end with either asking the user a quest
21882257
NOTE: At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
21892258
</system-reminder>`,
21902259
synthetic: true,
2260+
...(nonAnthropic ? { ignored: true } : {}),
21912261
})
21922262
userMessage.parts.push(part)
2193-
return input.messages
2263+
trustedReminderParts.push(part as MessageV2.TextPart)
2264+
return { messages: input.messages, trustedReminderParts }
21942265
}
2195-
return input.messages
2266+
return { messages: input.messages, trustedReminderParts }
21962267
}
2268+
// altimate_change end
21972269

21982270
export const ShellInput = z.object({
21992271
sessionID: SessionID.zod,

‎packages/opencode/src/session/prompt/plan-reminder-anthropic.txt‎

Lines changed: 0 additions & 67 deletions
This file was deleted.

‎packages/opencode/src/session/prompt/plan.txt‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,22 @@ Ask the user clarifying questions or ask for their opinion when weighing tradeof
2020

2121
---
2222

23+
// altimate_change start — mandatory exploration before drafting
24+
## Investigate before drafting (REQUIRED)
25+
26+
Before you write any plan content — outline OR full plan — you MUST call at least one read-only investigation tool against the actual codebase. Acceptable first moves:
27+
28+
- `read` / `grep` / `glob` / `list` on relevant files
29+
- launching one or more `explore` subagents in parallel for broader sweeps
30+
- `bash` for read-only inspection (e.g. `git log`, `git diff`, `ls`)
31+
32+
Plans written from the prompt alone — without inspecting the repo — are guesswork. They reference files that may not exist, miss existing patterns, and waste the user's time. If the task is trivial enough that you genuinely have everything needed (e.g. the user pasted the exact file contents inline), say so explicitly before drafting.
33+
34+
This applies on the very first step. Do not produce a plan, an outline, or a "summary of approach" as your first action.
35+
// altimate_change end
36+
37+
---
38+
2339
// altimate_change start — two-step plan approach with refinement loop
2440
## Two-Step Plan Approach
2541

0 commit comments

Comments
 (0)