Remove keyword/params hooks, add planning state

This commit is contained in:
Chris Scott committed 2026-02-24 21:13:27 -05:00
1 parent 0a4be46fd3
commit 745b883052
5 files changed
+100 -440

No files matched your search

-2
View File
@@ -1,6 +1,4 @@
export { createSessionHooks, type SessionHooks } from './session'
export { createKeywordHooks, type KeywordHooks, ACTIVATION_CONTEXT } from './keyword'
export { createParamsHooks, type ParamsHooks } from './params'
export {
buildCustomCompactionPrompt,
formatPlanningState,
-127
View File
@@ -1,127 +0,0 @@
import type { Logger } from '../types'
export interface KeywordHooks {
onMessage: (input: unknown, output: unknown) => Promise<void>
isActivated: (sessionId: string) => boolean
getMode: (sessionId: string) => string | undefined
}
interface TextPart {
type: 'text'
text: string
synthetic?: boolean
ignored?: boolean
}
interface ChatMessageInput {
sessionID?: string
agent?: string
messageID?: string
}
interface ChatMessageOutput {
message?: { id?: string; role: string; sessionID?: string }
parts?: Array<TextPart>
}
interface ActivationState {
activated: boolean
mode?: string
}
const KEYWORD_PATTERNS = [
/remember\s+(this|that)/i,
/recall/i,
/what\s+do\s+you\s+know\s+about/i,
/project\s+memory/i,
/do\s+you\s+remember/i,
/stored\s+memory/i,
/from\s+memory/i,
]
export const ACTIVATION_CONTEXT = `## Project Memory Available
This project has a memory system that stores architectural decisions, conventions, and patterns. You have access to:
- memory-read: Search and retrieve project memories
- memory-write: Store new project memories as suggestions
- memory-delete: Delete a memory by ID
Memory scopes: convention, decision, context
When relevant, use these tools to provide context from the project's knowledge base.`
const MODE_PATTERNS: Record<string, RegExp[]> = {
creative: [
/brainstorm/i,
/be\s+creative/i,
/explore\s+options/i,
/generate\s+ideas/i,
],
deepThink: [
/think\s+hard/i,
/think\s+deeply/i,
/analyze\s+carefully/i,
/think\s+through/i,
],
thorough: [
/go\s+deep/i,
/be\s+thorough/i,
/take\s+your\s+time/i,
],
}
export function createKeywordHooks(logger: Logger): KeywordHooks {
const sessionStateMap = new Map<string, ActivationState>()
return {
async onMessage(input, output) {
const chatInput = input as ChatMessageInput
const chatOutput = output as ChatMessageOutput
const sessionId = chatInput.sessionID
if (!sessionId) return
const existingState = sessionStateMap.get(sessionId)
if (existingState?.activated && existingState.mode) return
const parts = chatOutput.parts ?? []
const textParts = parts.filter((p): p is TextPart => {
if (p.type !== 'text') return false
return typeof p.text === 'string' && p.text.length > 0
})
const userContent = textParts.map(p => p.text).join(' ')
if (!userContent) return
const hasKeyword = KEYWORD_PATTERNS.some((pattern) => pattern.test(userContent))
const matchedModeEntry = Object.entries(MODE_PATTERNS).find(([, patterns]) =>
patterns.some((pattern) => pattern.test(userContent))
)
const matchedMode = matchedModeEntry?.[0]
if (!hasKeyword && !matchedMode) return
const state = sessionStateMap.get(sessionId) ?? { activated: false }
if (hasKeyword && !state.activated) {
logger.log(`Keyword match detected in session ${sessionId}, setting activation flag`)
state.activated = true
}
if (matchedMode && !state.mode) {
logger.log(`Mode pattern detected in session ${sessionId}: ${matchedMode}`)
state.mode = matchedMode
}
sessionStateMap.set(sessionId, state)
},
isActivated(sessionId: string): boolean {
return sessionStateMap.get(sessionId)?.activated ?? false
},
getMode(sessionId: string): string | undefined {
return sessionStateMap.get(sessionId)?.mode
},
}
}
-73
View File
@@ -1,73 +0,0 @@
import type { KeywordHooks } from './keyword'
export interface ParamsHooks {
onParams: (input: unknown, output: unknown) => Promise<void>
}
interface ChatParamsInput {
sessionID?: string
agent: string
}
interface ChatParamsOutput {
temperature?: number
topP?: number
topK?: number
options?: Record<string, any>
}
type ModeConfig = {
temperature?: number
maxSteps?: number
thinkingBudgetTokens?: number
}
const MODE_CONFIGS: Record<string, ModeConfig> = {
creative: {
temperature: 0.8,
},
deepThink: {
thinkingBudgetTokens: 32000,
},
thorough: {
maxSteps: 50,
},
}
export function createParamsHooks(keywordHooks: KeywordHooks): ParamsHooks {
return {
async onParams(input, output) {
const paramsInput = input as ChatParamsInput
const paramsOutput = output as ChatParamsOutput
const sessionId = paramsInput.sessionID
if (!sessionId) return
const mode = keywordHooks.getMode(sessionId)
if (!mode) return
const config = MODE_CONFIGS[mode]
if (!config) return
if (config.temperature !== undefined) {
paramsOutput.temperature = config.temperature
}
if (config.maxSteps !== undefined) {
if (!paramsOutput.options) {
paramsOutput.options = {}
}
paramsOutput.options.maxSteps = config.maxSteps
}
if (config.thinkingBudgetTokens !== undefined) {
if (!paramsOutput.options) {
paramsOutput.options = {}
}
paramsOutput.options.thinking = {
budgetTokens: config.thinkingBudgetTokens,
}
}
},
}
}
+19 -4
View File
@@ -52,11 +52,21 @@ function formatEventProperties(props?: Record<string, unknown>): string {
}
}
function buildSubtaskPrompt(sessionId: string, compactionSummary: string): string {
return `Review the following compaction summary and extract any project knowledge worth preserving across sessions.
function buildSubtaskPrompt(
sessionId: string,
compactionSummary: string,
planningState: PlanningState | null
): string {
const planningSection = planningState
? `## Current Planning State\n\n${formatPlanningState(planningState) ?? '(no details)'}\n\n---\n`
: ''
return `Review the following and extract any project knowledge worth preserving across sessions.
${planningSection}## Compaction Summary
---
${compactionSummary}
---
For each item found, store it with the appropriate scope:
@@ -109,6 +119,11 @@ export function createSessionHooks(
logger.log(`Post-compaction: fetched compaction summary (${compactionSummary.length} chars)`)
const planningState = sessionStateService.getPlanningState(sessionId)
if (planningState) {
logger.log(`Post-compaction: fetched planning state for session ${sessionId}`)
}
await ctx.client.session.prompt({
path: { id: sessionId },
body: {
@@ -117,7 +132,7 @@ export function createSessionHooks(
type: 'subtask',
agent: 'Memory',
description: 'Memory extraction after compaction',
prompt: buildSubtaskPrompt(sessionId, compactionSummary),
prompt: buildSubtaskPrompt(sessionId, compactionSummary, planningState),
},
],
},
+81 -234
View File
@@ -1,10 +1,8 @@
import { describe, test, expect, beforeEach } from 'bun:test'
import { createKeywordHooks } from '../src/hooks/keyword'
import { createParamsHooks } from '../src/hooks/params'
import { createSessionHooks } from '../src/hooks/session'
import type { MemoryService } from '../src/services/memory'
import type { SessionStateService } from '../src/services/session-state'
import type { Logger, Memory, MemoryScope } from '../src/types'
import type { Logger, Memory, MemoryScope, PlanningState } from '../src/types'
import type { PluginInput } from '@opencode-ai/plugin'
const TEST_PROJECT_ID = 'test-project-id'
@@ -20,6 +18,12 @@ const mockSessionStateService = {
setCompactionSnapshot: () => {},
} as unknown as SessionStateService
const createMockSessionStateServiceWithPlanning = (planningState: PlanningState | null): SessionStateService => ({
getPlanningState: () => planningState,
getCompactionSnapshot: () => null,
setCompactionSnapshot: () => {},
} as unknown as SessionStateService)
const mockPromptAsync = async () => {}
const mockPluginInput: PluginInput = {
@@ -103,226 +107,6 @@ const mockMemories: Memory[] = [
},
]
describe('KeywordHooks', () => {
test('Keyword hook detects "remember this" and sets activation flag', async () => {
const hooks = createKeywordHooks(mockLogger)
const input = {
sessionID: 'test-session',
}
const output = {
message: { id: 'msg-1', sessionID: 'test-session', role: 'user' },
parts: [
{ id: 'p1', sessionID: 'test-session', messageID: 'msg-1', type: 'text', text: 'Remember this: we use PostgreSQL for the database' },
],
}
await hooks.onMessage(input, output)
expect(hooks.isActivated('test-session')).toBe(true)
})
test('Keyword hook detects "do you know about" pattern', async () => {
const hooks = createKeywordHooks(mockLogger)
const input = {
sessionID: 'test-session',
}
const output = {
message: { id: 'msg-1', sessionID: 'test-session', role: 'user' },
parts: [
{ id: 'p1', sessionID: 'test-session', messageID: 'msg-1', type: 'text', text: 'What do you know about the authentication system?' },
],
}
await hooks.onMessage(input, output)
expect(hooks.isActivated('test-session')).toBe(true)
})
test('Keyword hook detects "project memory" pattern', async () => {
const hooks = createKeywordHooks(mockLogger)
const input = {
sessionID: 'test-session',
}
const output = {
message: { id: 'msg-1', sessionID: 'test-session', role: 'user' },
parts: [
{ id: 'p1', sessionID: 'test-session', messageID: 'msg-1', type: 'text', text: 'Check the project memory for API conventions' },
],
}
await hooks.onMessage(input, output)
expect(hooks.isActivated('test-session')).toBe(true)
})
test('Keyword hook does not trigger for normal messages', async () => {
const hooks = createKeywordHooks(mockLogger)
const input = {
sessionID: 'test-session',
}
const output = {
message: { id: 'msg-1', sessionID: 'test-session', role: 'user' },
parts: [
{ id: 'p1', sessionID: 'test-session', messageID: 'msg-1', type: 'text', text: 'Hello, how are you?' },
],
}
await hooks.onMessage(input, output)
expect(hooks.isActivated('test-session')).toBe(false)
})
test('Keyword hook only triggers once per session', async () => {
const hooks = createKeywordHooks(mockLogger)
const input1 = {
sessionID: 'test-session',
}
const output1 = {
message: { id: 'msg-1', sessionID: 'test-session', role: 'user' },
parts: [
{ id: 'p1', sessionID: 'test-session', messageID: 'msg-1', type: 'text', text: 'Remember this: use ESLint' },
],
}
await hooks.onMessage(input1, output1)
expect(hooks.isActivated('test-session')).toBe(true)
const input2 = {
sessionID: 'test-session',
}
const output2 = {
message: { id: 'msg-2', sessionID: 'test-session', role: 'user' },
parts: [
{ id: 'p2', sessionID: 'test-session', messageID: 'msg-2', type: 'text', text: 'Remember: use Prettier' },
],
}
await hooks.onMessage(input2, output2)
expect(hooks.isActivated('test-session')).toBe(true)
})
test('Keyword hook detects mode patterns', async () => {
const hooks = createKeywordHooks(mockLogger)
const input = {
sessionID: 'test-session',
}
const output = {
message: { id: 'msg-1', sessionID: 'test-session', role: 'user' },
parts: [
{ id: 'p1', sessionID: 'test-session', messageID: 'msg-1', type: 'text', text: 'Brainstorm some ideas for the UI' },
],
}
await hooks.onMessage(input, output)
expect(hooks.getMode('test-session')).toBe('creative')
})
})
describe('ParamsHooks', () => {
test('Params hook adjusts temperature for creative mode', async () => {
const keywordHooks = createKeywordHooks(mockLogger)
const hooks = createParamsHooks(keywordHooks)
keywordHooks.onMessage(
{ sessionID: 'test-session' },
{
message: { id: 'msg-1', sessionID: 'test-session', role: 'user' },
parts: [{ id: 'p1', sessionID: 'test-session', messageID: 'msg-1', type: 'text', text: 'Brainstorm some ideas' }],
}
)
const input = {
sessionID: 'test-session',
agent: 'test',
}
const output: { temperature?: number; options?: Record<string, any> } = {}
await hooks.onParams(input, output)
expect(output.temperature).toBe(0.8)
})
test('Params hook adjusts thinking for deepThink mode', async () => {
const keywordHooks = createKeywordHooks(mockLogger)
const hooks = createParamsHooks(keywordHooks)
keywordHooks.onMessage(
{ sessionID: 'test-session' },
{
message: { id: 'msg-1', sessionID: 'test-session', role: 'user' },
parts: [{ id: 'p1', sessionID: 'test-session', messageID: 'msg-1', type: 'text', text: 'Think hard about this' }],
}
)
const input = {
sessionID: 'test-session',
agent: 'test',
}
const output: { options?: { thinking?: { budgetTokens?: number } } } = {}
await hooks.onParams(input, output)
expect(output.options?.thinking?.budgetTokens).toBe(32000)
})
test('Params hook adjusts maxSteps for thorough mode', async () => {
const keywordHooks = createKeywordHooks(mockLogger)
const hooks = createParamsHooks(keywordHooks)
keywordHooks.onMessage(
{ sessionID: 'test-session' },
{
message: { id: 'msg-1', sessionID: 'test-session', role: 'user' },
parts: [{ id: 'p1', sessionID: 'test-session', messageID: 'msg-1', type: 'text', text: 'Go deep and be thorough' }],
}
)
const input = {
sessionID: 'test-session',
agent: 'test',
}
const output: { options?: { maxSteps?: number } } = {}
await hooks.onParams(input, output)
expect(output.options?.maxSteps).toBe(50)
})
test('Params hook does not adjust for normal messages', async () => {
const keywordHooks = createKeywordHooks(mockLogger)
const hooks = createParamsHooks(keywordHooks)
const input = {
sessionID: 'test-session',
agent: 'test',
}
const output: { temperature?: number; options?: Record<string, any> } = {}
await hooks.onParams(input, output)
expect(output.temperature).toBeUndefined()
expect(output.options).toBeUndefined()
})
})
describe('SessionHooks', () => {
test('Session compacting hook includes memory sections in context', async () => {
const memoryService = createMockMemoryService(mockMemories)
@@ -398,7 +182,6 @@ describe('SessionHooks', () => {
return { data: { parts: [{ type: 'text', text: 'Done' }] } }
},
promptAsync: async () => {},
todo: async () => ({ data: [] }),
},
app: {
log: () => {},
@@ -432,9 +215,80 @@ describe('SessionHooks', () => {
expect(call.body.parts.length).toBe(1)
})
test('session.compacted with active todos includes resume instruction', async () => {
test('session.compacted includes planning state in subtask prompt when available', async () => {
let promptCall: unknown = null
const planningState: PlanningState = {
objective: 'Refactor memory extraction flow',
current: 'Updating buildSubtaskPrompt to accept planning state',
next: 'Run tests and verify behavior',
phases: [
{ title: 'Update buildSubtaskPrompt', status: 'completed', notes: 'Added planningState parameter' },
{ title: 'Update runPostCompactionFlow', status: 'in_progress', notes: 'Fetching from KV store' },
{ title: 'Add tests', status: 'pending' },
],
findings: ['SubtaskPart keeps session busy'],
errors: [],
}
const customMockPluginInput: PluginInput = {
client: {
session: {
messages: async () => ({
data: [
{ info: { role: 'assistant' }, parts: [{ type: 'text', text: 'Compaction summary here' }] },
],
}),
create: async () => ({ data: { id: 'unused' } }),
prompt: async (call: unknown) => {
promptCall = call
return { data: { parts: [{ type: 'text', text: 'Done' }] } }
},
promptAsync: async () => {},
},
app: {
log: () => {},
},
},
project: { id: TEST_PROJECT_ID, worktree: '/test' },
directory: '/test',
worktree: '/test',
serverUrl: new URL('http://localhost:5551'),
} as unknown as PluginInput
const memoryService = createMockMemoryService([])
const sessionStateWithPlanning = createMockSessionStateServiceWithPlanning(planningState)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, sessionStateWithPlanning, mockLogger, customMockPluginInput)
await hooks.onEvent({
event: { type: 'session.compacted', properties: { sessionId: 'test-session-planning' } },
})
await new Promise(resolve => setTimeout(resolve, 50))
expect(promptCall).not.toBeNull()
const call = promptCall as any
const subtask = call.body.parts[0]
expect(subtask.prompt).toContain('Current Planning State')
expect(subtask.prompt).toContain('Refactor memory extraction flow')
expect(subtask.prompt).toContain('Updating buildSubtaskPrompt')
expect(subtask.prompt).toContain('[x] Update buildSubtaskPrompt')
expect(subtask.prompt).toContain('[~] Update runPostCompactionFlow')
})
test('session.compacted with active planning includes resume instruction', async () => {
let promptCall: unknown = null
const planningState: PlanningState = {
objective: 'Complete the refactor',
current: 'Running tests',
next: 'Commit changes',
phases: [
{ title: 'Phase 1', status: 'completed' },
{ title: 'Phase 2', status: 'in_progress', notes: 'Almost done' },
],
}
const customMockPluginInput: PluginInput = {
client: {
session: {
@@ -449,12 +303,6 @@ describe('SessionHooks', () => {
return { data: { parts: [{ type: 'text', text: 'Done' }] } }
},
promptAsync: async () => {},
todo: async () => ({
data: [
{ status: 'completed', content: 'Done task', priority: 'high', id: '1' },
{ status: 'in_progress', content: 'Active task', priority: 'high', id: '2' },
],
}),
},
app: {
log: () => {},
@@ -467,7 +315,8 @@ describe('SessionHooks', () => {
} as unknown as PluginInput
const memoryService = createMockMemoryService([])
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, customMockPluginInput)
const sessionStateWithPlanning = createMockSessionStateServiceWithPlanning(planningState)
const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, sessionStateWithPlanning, mockLogger, customMockPluginInput)
await hooks.onEvent({
event: { type: 'session.compacted', properties: { sessionId: 'test-session-active' } },
@@ -494,7 +343,6 @@ describe('SessionHooks', () => {
return { data: { parts: [] } }
},
promptAsync: async () => {},
todo: async () => ({ data: [] }),
},
app: {
log: () => {},
@@ -534,7 +382,6 @@ describe('SessionHooks', () => {
return { data: { parts: [] } }
},
promptAsync: async () => {},
todo: async () => ({ data: [] }),
},
app: {
log: () => {},