Inject read-only reminder into Architect messages, use constant for agent name, defensive state re-read

This commit is contained in:
Chris Scott committed 2026-02-27 12:45:11 -05:00
1 parent d149c94eac
commit 4cb2ed7efd
2 files changed
+159 -10

No files matched your search

+49 -10
View File
@@ -604,10 +604,17 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
},
}),
'memory-plan-execute': tool({
description: 'Create a new Code session and send the plan as the first prompt. Call this after the user approves the plan.',
description: 'Create a new Code session, save planning state, and send the plan as the first prompt. Call this after the user approves the plan.',
args: {
plan: z.string().describe('The full implementation plan to send to the Code agent'),
title: z.string().describe('Short title for the session (shown in session list)'),
objective: z.string().optional().describe('Short description of what we are building'),
phases: z.array(z.object({
title: z.string(),
status: z.string(),
notes: z.string().optional(),
})).optional().describe('Phases from the plan, each with status "pending"'),
findings: z.array(z.string()).optional().describe('Key architectural decisions discovered during research'),
},
execute: async (args, context) => {
await initPromise
@@ -627,7 +634,17 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
const newSessionId = createResult.data.id
logger.log(`memory-plan-execute: created session=${newSessionId}`)
const planningInstruction = `\n\n---\n\nWhen you complete each phase, update the planning state using memory-planning-update with sessionID "${context.sessionID}". Update phase statuses as you progress (pending → in_progress → completed). Set current to describe what you're working on. When all work is done, set current to "Completed".`
const planningState: PlanningState = {
...(args.objective && { objective: args.objective }),
current: `Plan approved, sending to Code agent`,
...(args.phases && { phases: args.phases }),
...(args.findings && { findings: args.findings }),
active: true,
}
sessionStateService.setPlanningState(context.sessionID, projectId, planningState)
logger.log(`memory-plan-execute: saved planning state for session=${context.sessionID}`)
const planningInstruction = `\n\n---\n\nWhen you complete each phase, delegate to the @Memory subagent via the Task tool to update planning state. Tell it to call memory-planning-update with sessionID "${context.sessionID}". Update phase statuses as you progress (pending → in_progress → completed). Set current to describe what you're working on. When all work is done, set current to "Completed".`
const promptResult = await client.session.promptAsync({
path: { id: newSessionId },
@@ -644,14 +661,12 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
logger.log(`memory-plan-execute: prompted session=${newSessionId}`)
const existingState = sessionStateService.getPlanningState(context.sessionID, projectId)
if (existingState) {
sessionStateService.setPlanningState(context.sessionID, projectId, {
...existingState,
current: `Plan sent to execution session ${newSessionId}`,
})
logger.log(`memory-plan-execute: updated planning state for source session=${context.sessionID}`)
}
const currentState = sessionStateService.getPlanningState(context.sessionID, projectId)
sessionStateService.setPlanningState(context.sessionID, projectId, {
...(currentState ?? planningState),
current: `Plan sent to execution session ${newSessionId}`,
})
logger.log(`memory-plan-execute: updated planning state for source session=${context.sessionID}`)
return `Implementation session created and plan sent.\n\nSession: ${newSessionId}\nTitle: ${sessionTitle}\n\nSwitch to this session to begin. You can change the model from the session dropdown.`
},
@@ -674,6 +689,30 @@ export function createMemoryPlugin(config: PluginConfig): Plugin {
output as { context: string[]; prompt?: string }
)
},
'experimental.chat.messages.transform': async (
_input: Record<string, never>,
output: { messages: Array<{ info: { role: string; agent?: string }; parts: Array<Record<string, unknown>> }> }
) => {
const messages = output.messages
let userMessage: typeof messages[number] | undefined
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].info.role === 'user') {
userMessage = messages[i]
break
}
}
if (!userMessage || userMessage.info.agent !== agents.architect.displayName) return
userMessage.parts.push({
type: 'text',
text: `<system-reminder>
Plan mode is active. You MUST NOT make any file edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
You may ONLY: observe, analyze, plan, and use memory tools (memory-read, memory-write, memory-edit, memory-delete, memory-health, memory-planning-get, memory-plan-execute).
</system-reminder>`,
synthetic: true,
})
},
} as Hooks & { getCleanup: () => Promise<void> }
}
}
+110
View File
@@ -2,6 +2,7 @@ import { describe, test, expect, beforeEach, afterEach } from 'bun:test'
import { createMemoryPlugin } from '../src/index'
import { mkdirSync, rmSync, existsSync } from 'fs'
import type { PluginConfig } from '../src/types'
import type { PluginInput } from '@opencode-ai/plugin'
const TEST_DIR = '/tmp/opencode-manager-memory-test-' + Date.now()
@@ -409,3 +410,112 @@ describe('PluginConfig', () => {
expect(config.dataDir).toBe('/custom/path/memory')
})
})
describe('messages.transform hook', () => {
let testDir: string
let hooks: Record<string, Function> & { getCleanup?: () => Promise<void> }
beforeEach(async () => {
testDir = TEST_DIR + '-transform-' + Math.random().toString(36).slice(2)
mkdirSync(testDir, { recursive: true })
const config: PluginConfig = {
embedding: {
provider: 'openai',
model: 'text-embedding-3-small',
dimensions: 1536,
apiKey: 'test-key',
},
dataDir: testDir,
}
const factory = createMemoryPlugin(config)
hooks = await factory({
client: {
session: {
prompt: async () => ({ data: { parts: [{ type: 'text', text: 'ok' }] } }),
promptAsync: async () => {},
messages: async () => ({ data: [] }),
create: async () => ({ data: { id: 'test-session' } }),
todo: async () => ({ data: [] }),
},
app: { log: () => {} },
},
project: { id: TEST_PROJECT_ID, worktree: testDir },
directory: testDir,
worktree: testDir,
serverUrl: new URL('http://localhost:5551'),
} as unknown as PluginInput) as any
})
afterEach(async () => {
if (hooks?.getCleanup) {
await hooks.getCleanup()
}
if (existsSync(testDir)) {
rmSync(testDir, { recursive: true, force: true })
}
})
test('injects system-reminder for Architect agent messages', async () => {
const output = {
messages: [
{ info: { role: 'assistant' }, parts: [{ type: 'text', text: 'hello' }] },
{ info: { role: 'user', agent: 'Architect' }, parts: [{ type: 'text', text: 'plan this' }] },
],
}
await hooks['experimental.chat.messages.transform']({}, output)
const userMsg = output.messages[1]
expect(userMsg.parts).toHaveLength(2)
expect(userMsg.parts[1]).toMatchObject({
type: 'text',
synthetic: true,
})
const text = userMsg.parts[1].text as string
expect(text).toContain('system-reminder')
expect(text).toContain('MUST NOT make any file edits')
expect(text).not.toContain('memory-planning-update')
expect(text).not.toContain('memory-planning-search')
})
test('does NOT inject for non-Architect agents', async () => {
const output = {
messages: [
{ info: { role: 'user', agent: 'Code' }, parts: [{ type: 'text', text: 'do something' }] },
],
}
await hooks['experimental.chat.messages.transform']({}, output)
expect(output.messages[0].parts).toHaveLength(1)
})
test('does NOT inject when no user message exists', async () => {
const output = {
messages: [
{ info: { role: 'assistant' }, parts: [{ type: 'text', text: 'response' }] },
],
}
await hooks['experimental.chat.messages.transform']({}, output)
expect(output.messages[0].parts).toHaveLength(1)
})
test('targets the LAST user message in the array', async () => {
const output = {
messages: [
{ info: { role: 'user', agent: 'Code' }, parts: [{ type: 'text', text: 'first' }] },
{ info: { role: 'assistant' }, parts: [{ type: 'text', text: 'response' }] },
{ info: { role: 'user', agent: 'Architect' }, parts: [{ type: 'text', text: 'second' }] },
],
}
await hooks['experimental.chat.messages.transform']({}, output)
expect(output.messages[0].parts).toHaveLength(1)
expect(output.messages[2].parts).toHaveLength(2)
})
})