From 4bbc86bc3965c8a29264e9a776c6ea3bea67df93 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 24 Feb 2026 19:07:47 -0500 Subject: [PATCH] refactor: use SubtaskPart for post-compaction memory extraction --- packages/memory/package.json | 2 +- packages/memory/src/hooks/compaction-utils.ts | 24 ++- packages/memory/src/hooks/index.ts | 1 + packages/memory/src/hooks/session.ts | 67 +++++-- packages/memory/src/version.ts | 2 +- packages/memory/test/compaction-utils.test.ts | 52 ++++++ packages/memory/test/hooks.test.ts | 172 ++++++++++++++---- 7 files changed, 267 insertions(+), 53 deletions(-) diff --git a/packages/memory/package.json b/packages/memory/package.json index d2fc6572..620c09a7 100644 --- a/packages/memory/package.json +++ b/packages/memory/package.json @@ -1,6 +1,6 @@ { "name": "@opencode-manager/memory", - "version": "0.0.5", + "version": "0.0.6", "type": "module", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/packages/memory/src/hooks/compaction-utils.ts b/packages/memory/src/hooks/compaction-utils.ts index 2c728523..946c5a71 100644 --- a/packages/memory/src/hooks/compaction-utils.ts +++ b/packages/memory/src/hooks/compaction-utils.ts @@ -1,5 +1,15 @@ import type { PlanningState } from '../types' +interface PromptResponsePart { + type: string + text?: string +} + +interface SessionMessage { + info: { role: string } + parts: PromptResponsePart[] +} + export function buildCustomCompactionPrompt(): string { return `You are generating a continuation context for a coding session with persistent project memory. Your summary will be the ONLY context after compaction. @@ -31,7 +41,7 @@ Preserve everything needed for seamless continuation. [What should happen immediately after compaction] ## Rules -- Use specific file paths, phase names - NOT vague references +- Use specific file paths. - State what tools returned, not just that they were called - Prefer completeness over brevity - this is the agent's entire working memory` } @@ -104,6 +114,18 @@ export function formatCompactionDiagnostics(stats: { return `> **Compaction preserved:** ${parts.join(', ')} (~${stats.tokensInjected} tokens injected)` } +export function extractCompactionSummary(messages: SessionMessage[]): string | null { + const reversed = [...messages].reverse() + for (const msg of reversed) { + if (msg.info.role !== 'assistant') continue + const textParts = msg.parts + .filter((p): p is PromptResponsePart & { text: string } => p.type === 'text' && typeof p.text === 'string') + .map(p => p.text) + if (textParts.length > 0) return textParts.join('\n') + } + return null +} + export function estimateTokens(text: string): number { return Math.ceil(text.length / 4) } diff --git a/packages/memory/src/hooks/index.ts b/packages/memory/src/hooks/index.ts index 34592cd4..8a110b74 100644 --- a/packages/memory/src/hooks/index.ts +++ b/packages/memory/src/hooks/index.ts @@ -7,4 +7,5 @@ export { formatCompactionDiagnostics, estimateTokens, trimToTokenBudget, + extractCompactionSummary, } from './compaction-utils' diff --git a/packages/memory/src/hooks/session.ts b/packages/memory/src/hooks/session.ts index a55bfa72..29aa56d6 100644 --- a/packages/memory/src/hooks/session.ts +++ b/packages/memory/src/hooks/session.ts @@ -8,6 +8,7 @@ import { formatCompactionDiagnostics, estimateTokens, trimToTokenBudget, + extractCompactionSummary, } from './compaction-utils' export interface SessionHooks { @@ -51,22 +52,25 @@ function formatEventProperties(props?: Record): string { } } -function buildExtractionPrompt(sessionId: string): string { - return `[COMPACTION COMPLETE] +function buildSubtaskPrompt(sessionId: string, compactionSummary: string): string { + return `Review the following compaction summary and extract any project knowledge worth preserving across sessions. -The compaction summary above is now in your context window. - -Review the compaction summary and extract any project knowledge worth preserving across sessions. For each item found, use memory-write to store it with the appropriate scope: +--- +${compactionSummary} +--- +For each item found, store it with the appropriate scope: - convention: coding style rules, naming patterns, workflow preferences - decision: architectural choices with their rationale - context: project structure, key file locations, domain knowledge, known issues -Also extract any planning state (phases, objectives, progress, blockers) from the compaction summary. If found, use memory-planning-update with sessionID "${sessionId}" to store it. This creates continuity across compactions. +Also extract any planning state (phases, objectives, progress, blockers). If found, use memory-planning-update with sessionID "${sessionId}" to store it. -Be selective — only store knowledge that will be useful in future sessions. Skip ephemeral task details and session-specific notes. +Be selective — only store knowledge useful in future sessions. Check for duplicates before writing (use memory-read to search first). -Check for duplicates before writing (use memory-read to search). If a similar memory already exists, skip it.` +End your response with: +1. A brief summary of what was stored +2. Whether there was active work in progress (in-progress todos, pending tasks, or incomplete planning phases). If so, tell the main agent to review the planning state and todo list and continue where it left off.` } const DEFAULT_COMPACTION_CONFIG: CompactionConfig = { @@ -87,6 +91,41 @@ export function createSessionHooks( const initializedSessions = new Set() const compactionConfig = { ...DEFAULT_COMPACTION_CONFIG, ...config } + async function runPostCompactionFlow(sessionId: string): Promise { + const messagesResult = await ctx.client.session.messages({ + path: { id: sessionId }, + query: { limit: 4 }, + }) + + const messages = messagesResult.data as unknown as Array<{ + info: { role: string } + parts: Array<{ type: string; text?: string }> + }> + const compactionSummary = extractCompactionSummary(messages ?? []) + if (!compactionSummary) { + logger.log(`Post-compaction: no summary found in session ${sessionId}, skipping extraction`) + return + } + + logger.log(`Post-compaction: fetched compaction summary (${compactionSummary.length} chars)`) + + await ctx.client.session.prompt({ + path: { id: sessionId }, + body: { + parts: [ + { + type: 'subtask', + agent: 'Memory', + description: 'Memory extraction after compaction', + prompt: buildSubtaskPrompt(sessionId, compactionSummary), + }, + ], + }, + }) + + logger.log(`Post-compaction: extraction and resumption complete for session ${sessionId}`) + } + return { async onMessage(input, _output) { const chatInput = input as ChatMessageInput @@ -111,16 +150,10 @@ export function createSessionHooks( return } - logger.log(`Session compacted for project ${projectId} - extraction handled by Memory agent`) + logger.log(`Session compacted for project ${projectId} - starting isolated extraction`) - ctx.client.session.promptAsync({ - path: { id: sessionId }, - body: { - agent: 'Memory', - parts: [{ type: 'text', text: buildExtractionPrompt(sessionId) }], - }, - }).catch((err) => { - logger.error(`Failed to invoke memory extraction: ${err}`) + runPostCompactionFlow(sessionId).catch((err) => { + logger.error(`Post-compaction flow failed: ${err}`) }) }, async onCompacting(input: CompactingInput, output: CompactingOutput) { diff --git a/packages/memory/src/version.ts b/packages/memory/src/version.ts index 93fb7822..8946c40d 100644 --- a/packages/memory/src/version.ts +++ b/packages/memory/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.0.5' +export const VERSION = '0.0.6' diff --git a/packages/memory/test/compaction-utils.test.ts b/packages/memory/test/compaction-utils.test.ts index 3756c2c4..f064f213 100644 --- a/packages/memory/test/compaction-utils.test.ts +++ b/packages/memory/test/compaction-utils.test.ts @@ -5,6 +5,7 @@ import { formatCompactionDiagnostics, estimateTokens, trimToTokenBudget, + extractCompactionSummary, } from '../src/hooks/compaction-utils' import type { PlanningState } from '../src/types' @@ -166,3 +167,54 @@ describe('trimToTokenBudget', () => { expect(result).toContain('...') }) }) + +describe('extractCompactionSummary', () => { + test('extracts text from last assistant message', () => { + const messages = [ + { info: { role: 'user' }, parts: [{ type: 'text', text: 'User message' }] }, + { info: { role: 'assistant' }, parts: [{ type: 'text', text: 'Compaction summary here' }] }, + ] + const result = extractCompactionSummary(messages) + expect(result).toBe('Compaction summary here') + }) + + test('returns null when no assistant messages', () => { + const messages = [ + { info: { role: 'user' }, parts: [{ type: 'text', text: 'User message' }] }, + ] + const result = extractCompactionSummary(messages) + expect(result).toBeNull() + }) + + test('returns null for empty messages', () => { + expect(extractCompactionSummary([])).toBeNull() + }) + + test('concatenates multiple text parts', () => { + const messages = [ + { + info: { role: 'assistant' }, + parts: [ + { type: 'text', text: 'Part 1' }, + { type: 'tool', text: undefined }, + { type: 'text', text: 'Part 2' }, + ], + }, + ] + const result = extractCompactionSummary(messages) + expect(result).toBe('Part 1\nPart 2') + }) + + test('picks the last assistant message when multiple exist', () => { + const messages = [ + { info: { role: 'assistant' }, parts: [{ type: 'text', text: 'Old summary' }] }, + { info: { role: 'user' }, parts: [{ type: 'text', text: 'User msg' }] }, + { info: { role: 'assistant' }, parts: [{ type: 'text', text: 'Latest summary' }] }, + ] + const result = extractCompactionSummary(messages) + expect(result).toBe('Latest summary') + }) +}) + + + diff --git a/packages/memory/test/hooks.test.ts b/packages/memory/test/hooks.test.ts index e482b205..c1f1f6cb 100644 --- a/packages/memory/test/hooks.test.ts +++ b/packages/memory/test/hooks.test.ts @@ -25,8 +25,15 @@ const mockPromptAsync = async () => {} const mockPluginInput: PluginInput = { client: { session: { - prompt: async () => {}, + prompt: async () => ({ data: { parts: [{ type: 'text', text: 'Extracted memories' }] } }), promptAsync: mockPromptAsync, + messages: async () => ({ + data: [ + { info: { role: 'assistant' }, parts: [{ type: 'text', text: 'Compaction summary text' }] }, + ], + }), + create: async () => ({ data: { id: 'child-session-id' } }), + todo: async () => ({ data: [] }), }, app: { log: () => {}, @@ -374,16 +381,24 @@ describe('SessionHooks', () => { expect(true).toBe(true) }) - test('session.compacted event triggers promptAsync on the session with agent Memory', async () => { - let capturedCall: unknown = null - + test('session.compacted sends extraction prompt to main session via prompt()', async () => { + let promptCall: unknown = null + const customMockPluginInput: PluginInput = { client: { session: { - prompt: async () => {}, - promptAsync: async (call) => { - capturedCall = call as typeof capturedCall + messages: async () => ({ + data: [ + { info: { role: 'assistant' }, parts: [{ type: 'text', text: 'Compaction summary content' }] }, + ], + }), + create: async () => ({ data: { id: 'unused' } }), + prompt: async (call: unknown) => { + promptCall = call + return { data: { parts: [{ type: 'text', text: 'Done' }] } } }, + promptAsync: async () => {}, + todo: async () => ({ data: [] }), }, app: { log: () => {}, @@ -398,33 +413,48 @@ describe('SessionHooks', () => { const memoryService = createMockMemoryService([]) const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, customMockPluginInput) - const input = { - event: { - type: 'session.compacted', - properties: { sessionId: 'test-session-123' }, - }, - } + await hooks.onEvent({ + event: { type: 'session.compacted', properties: { sessionId: 'test-session-123' } }, + }) + await new Promise(resolve => setTimeout(resolve, 50)) - await hooks.onEvent(input) + expect(promptCall).not.toBeNull() + const call = promptCall as any + expect(call.path.id).toBe('test-session-123') - expect(capturedCall).not.toBeNull() - expect((capturedCall as any).path.id).toBe('test-session-123') - expect((capturedCall as any).body.agent).toBe('Memory') - expect((capturedCall as any).body.parts[0]?.type).toBe('text') - expect((capturedCall as any).body.parts[0]?.text).toContain('COMPACTION COMPLETE') - expect((capturedCall as any).body.parts[0]?.text).toContain('sessionID "test-session-123"') + const subtask = call.body.parts[0] + expect(subtask.type).toBe('subtask') + expect(subtask.agent).toBe('Memory') + expect(subtask.description).toBe('Memory extraction after compaction') + expect(subtask.prompt).toContain('Compaction summary content') + expect(subtask.prompt).toContain('sessionID "test-session-123"') + expect(subtask.prompt).toContain('active work in progress') + expect(call.body.parts.length).toBe(1) }) - test('session.compacted with missing sessionId does NOT call promptAsync', async () => { - let promptAsyncCalled = false - + test('session.compacted with active todos includes resume instruction', async () => { + let promptCall: unknown = null + const customMockPluginInput: PluginInput = { client: { session: { - prompt: async () => {}, - promptAsync: async () => { - promptAsyncCalled = true + messages: async () => ({ + data: [ + { info: { role: 'assistant' }, parts: [{ type: 'text', text: 'Summary' }] }, + ], + }), + create: async () => ({ data: { id: 'unused' } }), + prompt: async (call: unknown) => { + promptCall = call + 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: () => {}, @@ -439,15 +469,91 @@ describe('SessionHooks', () => { const memoryService = createMockMemoryService([]) const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, customMockPluginInput) - const input = { - event: { - type: 'session.compacted', - properties: {}, + await hooks.onEvent({ + event: { type: 'session.compacted', properties: { sessionId: 'test-session-active' } }, + }) + await new Promise(resolve => setTimeout(resolve, 50)) + + expect(promptCall).not.toBeNull() + const call = promptCall as any + expect(call.path.id).toBe('test-session-active') + expect(call.body.parts[0]?.type).toBe('subtask') + expect(call.body.parts[0]?.prompt).toContain('continue where it left off') + }) + + test('session.compacted with missing sessionId does NOT trigger flow', async () => { + let promptCalled = false + + const customMockPluginInput: PluginInput = { + client: { + session: { + messages: async () => ({ data: [] }), + create: async () => ({ data: { id: 'unused' } }), + prompt: async () => { + promptCalled = true + return { data: { parts: [] } } + }, + promptAsync: async () => {}, + todo: async () => ({ data: [] }), + }, + app: { + log: () => {}, + }, }, - } + project: { id: TEST_PROJECT_ID, worktree: '/test' }, + directory: '/test', + worktree: '/test', + serverUrl: new URL('http://localhost:5551'), + } as unknown as PluginInput - await hooks.onEvent(input) + const memoryService = createMockMemoryService([]) + const hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, customMockPluginInput) - expect(promptAsyncCalled).toBe(false) + await hooks.onEvent({ + event: { type: 'session.compacted', properties: {} }, + }) + await new Promise(resolve => setTimeout(resolve, 50)) + + expect(promptCalled).toBe(false) + }) + + test('session.compacted skips extraction when no compaction summary found', async () => { + let promptCalled = false + + const customMockPluginInput: PluginInput = { + client: { + session: { + messages: async () => ({ + data: [ + { info: { role: 'user' }, parts: [{ type: 'text', text: 'User only' }] }, + ], + }), + create: async () => ({ data: { id: 'unused' } }), + prompt: async () => { + promptCalled = true + return { data: { parts: [] } } + }, + promptAsync: async () => {}, + todo: async () => ({ data: [] }), + }, + 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 hooks = createSessionHooks(TEST_PROJECT_ID, memoryService, mockSessionStateService, mockLogger, customMockPluginInput) + + await hooks.onEvent({ + event: { type: 'session.compacted', properties: { sessionId: 'test-no-summary' } }, + }) + await new Promise(resolve => setTimeout(resolve, 50)) + + expect(promptCalled).toBe(false) }) })