Skip to content

Commit 64f72f2

Browse files
committed
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.
1 parent 77ffd92 commit 64f72f2

2 files changed

Lines changed: 86 additions & 43 deletions

File tree

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

Lines changed: 46 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -688,18 +688,25 @@ export namespace SessionPrompt {
688688
const agent = await Agent.get(lastUser.agent)
689689
const maxSteps = agent.steps ?? Infinity
690690
const isLastStep = step >= maxSteps
691-
msgs = await insertReminders({
691+
// altimate_change start — insertReminders now returns the trusted reminder
692+
// parts it appended; for non-Anthropic-like models we hoist them into the
693+
// system prompt and mark the parts ignored so they don't ALSO appear in
694+
// the user message. The returned-parts list is the trust boundary —
695+
// never the `synthetic` flag (other code paths set it on file/resource
696+
// expansions, which are user-derived). See #887/#888 review thread.
697+
const reminderResult = await insertReminders({
692698
messages: msgs,
693699
agent,
694700
session,
695701
})
696-
697-
// altimate_change start — hoist synthetic <system-reminder> parts into the
698-
// system prompt for non-Anthropic-like models. The synthetic flag is the
699-
// trust boundary: only parts written by insertReminders (PROMPT_PLAN /
700-
// BUILD_SWITCH) qualify; raw user text starting with `<system-reminder>`
701-
// is left untouched and never gains system-role priority. See #887/#888.
702-
const hoistedReminders = hoistSyntheticReminders(msgs, model)
702+
msgs = reminderResult.messages
703+
const hoistedReminders: string[] = []
704+
if (!isAnthropicLikeModel(model)) {
705+
for (const part of reminderResult.trustedReminderParts) {
706+
hoistedReminders.push(part.text)
707+
part.ignored = true
708+
}
709+
}
703710
// altimate_change end
704711

705712
// altimate_change start — plan refinement detection and telemetry
@@ -2048,7 +2055,7 @@ export namespace SessionPrompt {
20482055
}
20492056
}
20502057

2051-
// altimate_change start — trust-aware <system-reminder> hoist for non-Anthropic models
2058+
// altimate_change start — model-family helper used by the trust-aware hoist below
20522059
function isAnthropicLikeModel(model: Provider.Model): boolean {
20532060
return (
20542061
model.providerID === "anthropic" ||
@@ -2059,60 +2066,53 @@ export namespace SessionPrompt {
20592066
model.api.id.includes("claude")
20602067
)
20612068
}
2062-
2063-
function hoistSyntheticReminders(messages: MessageV2.WithParts[], model: Provider.Model): string[] {
2064-
// Anthropic-family models recognize <system-reminder>...</system-reminder> on a
2065-
// user-role text part as authoritative — keep that behavior unchanged.
2066-
// Other models (observed: GPT-5.x via altimate-backend gateway) pattern-match
2067-
// those tags inside user content as prompt-injection attempts and refuse.
2068-
// For them, lift our internally-generated reminders into a proper system-role
2069-
// message. The synthetic flag is the trust boundary — only parts we ourselves
2070-
// wrote in insertReminders qualify; raw user text starting with the same
2071-
// characters is left intact and never gains system priority.
2072-
if (isAnthropicLikeModel(model)) return []
2073-
const hoisted: string[] = []
2074-
for (const msg of messages) {
2075-
if (msg.info.role !== "user") continue
2076-
for (const part of msg.parts) {
2077-
if (part.type !== "text") continue
2078-
if (!part.synthetic) continue
2079-
if (!part.text.trimStart().startsWith("<system-reminder>")) continue
2080-
hoisted.push(part.text)
2081-
part.ignored = true
2082-
}
2083-
}
2084-
return hoisted
2085-
}
20862069
// altimate_change end
20872070

2088-
async function insertReminders(input: { messages: MessageV2.WithParts[]; agent: Agent.Info; session: Session.Info }) {
2071+
// altimate_change start — return the trusted reminder parts insertReminders just appended
2072+
// so the caller can hoist them into the system prompt on non-Anthropic models.
2073+
// The returned-parts contract is the trust boundary: only parts that *this function*
2074+
// creates are eligible for promotion. The schema-wide `synthetic` flag is set by other
2075+
// code paths too (file/resource expansions at lines ~1729/1751/1801 attach
2076+
// file content as synthetic text), so it is not safe to infer trust from `synthetic`
2077+
// alone. See #888 review feedback.
2078+
type InsertRemindersResult = { messages: MessageV2.WithParts[]; trustedReminderParts: MessageV2.TextPart[] }
2079+
async function insertReminders(input: {
2080+
messages: MessageV2.WithParts[]
2081+
agent: Agent.Info
2082+
session: Session.Info
2083+
}): Promise<InsertRemindersResult> {
2084+
const trustedReminderParts: MessageV2.TextPart[] = []
20892085
const userMessage = input.messages.findLast((msg) => msg.info.role === "user")
2090-
if (!userMessage) return input.messages
2086+
if (!userMessage) return { messages: input.messages, trustedReminderParts }
20912087

20922088
// Original logic when experimental plan mode is disabled
20932089
if (!Flag.OPENCODE_EXPERIMENTAL_PLAN_MODE) {
20942090
if (input.agent.name === "plan") {
2095-
userMessage.parts.push({
2091+
const part: MessageV2.TextPart = {
20962092
id: PartID.ascending(),
20972093
messageID: userMessage.info.id,
20982094
sessionID: userMessage.info.sessionID,
20992095
type: "text",
21002096
text: PROMPT_PLAN,
21012097
synthetic: true,
2102-
})
2098+
}
2099+
userMessage.parts.push(part)
2100+
trustedReminderParts.push(part)
21032101
}
21042102
const wasPlan = input.messages.some((msg) => msg.info.role === "assistant" && msg.info.agent === "plan")
21052103
if (wasPlan && input.agent.name === "builder") {
2106-
userMessage.parts.push({
2104+
const part: MessageV2.TextPart = {
21072105
id: PartID.ascending(),
21082106
messageID: userMessage.info.id,
21092107
sessionID: userMessage.info.sessionID,
21102108
type: "text",
21112109
text: BUILD_SWITCH,
21122110
synthetic: true,
2113-
})
2111+
}
2112+
userMessage.parts.push(part)
2113+
trustedReminderParts.push(part)
21142114
}
2115-
return input.messages
2115+
return { messages: input.messages, trustedReminderParts }
21162116
}
21172117

21182118
// New plan mode logic when flag is enabled
@@ -2133,8 +2133,9 @@ export namespace SessionPrompt {
21332133
synthetic: true,
21342134
})
21352135
userMessage.parts.push(part)
2136+
trustedReminderParts.push(part as MessageV2.TextPart)
21362137
}
2137-
return input.messages
2138+
return { messages: input.messages, trustedReminderParts }
21382139
}
21392140

21402141
// Entering plan mode
@@ -2236,10 +2237,12 @@ NOTE: At any point in time through this workflow you should feel free to ask the
22362237
synthetic: true,
22372238
})
22382239
userMessage.parts.push(part)
2239-
return input.messages
2240+
trustedReminderParts.push(part as MessageV2.TextPart)
2241+
return { messages: input.messages, trustedReminderParts }
22402242
}
2241-
return input.messages
2243+
return { messages: input.messages, trustedReminderParts }
22422244
}
2245+
// altimate_change end
22432246

22442247
export const ShellInput = z.object({
22452248
sessionID: SessionID.zod,

‎packages/opencode/test/session/plan-layer-e2e.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,6 +455,46 @@ describe("plan prompt safety", () => {
455455
)
456456
expect(planTxt).not.toMatch(/TODO|FIXME|HACK|XXX|console\.log/i)
457457
})
458+
459+
// Regression guards for the #888 review trust boundary.
460+
//
461+
// Background: PROMPT_PLAN / BUILD_SWITCH are attached as user-message text
462+
// parts wrapped in `<system-reminder>...</system-reminder>`. On non-Anthropic
463+
// models we hoist those into the system prompt so the model doesn't pattern-
464+
// match the tag as a prompt-injection attempt and refuse. Trust provenance
465+
// for the hoist MUST be the explicit list of parts returned by
466+
// `insertReminders` — never `synthetic + prefix`, because other code paths
467+
// (file/resource expansions around prompt.ts:1729/1751/1801) mark user-derived
468+
// content as synthetic. See PR #888 review thread.
469+
test("loop hoists ONLY parts returned by insertReminders, never scans for `synthetic`", async () => {
470+
const promptTs = await fs.readFile(
471+
path.join(__dirname, "../../src/session/prompt.ts"),
472+
"utf-8",
473+
)
474+
// Must consume the trusted-parts contract.
475+
expect(promptTs).toMatch(/trustedReminderParts/)
476+
// The hoist loop must iterate the returned trusted parts.
477+
expect(promptTs).toMatch(/for \(const part of reminderResult\.trustedReminderParts\)/)
478+
// The hoist must NOT have been re-implemented as a scan over `part.synthetic`,
479+
// which would re-open the prompt-injection vector via attached file content.
480+
expect(promptTs).not.toMatch(/hoistSyntheticReminders/)
481+
// The loose `if (!part.synthetic) continue` shape must not reappear in any
482+
// trust-boundary context. The remaining `synthetic` usages should only be
483+
// setters or the unrelated text-wrap skip at the queued-message reminder.
484+
})
485+
486+
test("insertReminders return shape includes trustedReminderParts", async () => {
487+
const promptTs = await fs.readFile(
488+
path.join(__dirname, "../../src/session/prompt.ts"),
489+
"utf-8",
490+
)
491+
expect(promptTs).toMatch(
492+
/async function insertReminders\([\s\S]*?\): Promise<InsertRemindersResult>/,
493+
)
494+
expect(promptTs).toMatch(
495+
/type InsertRemindersResult = \{ messages: MessageV2\.WithParts\[\]; trustedReminderParts: MessageV2\.TextPart\[\] \}/,
496+
)
497+
})
458498
})
459499

460500
// ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)