From ea21f0fa03c7fc0991e203cb1307fdcb19f47411 Mon Sep 17 00:00:00 2001 From: chen <54944284+chen893@users.noreply.github.com> Date: Sat, 30 Aug 2025 01:35:00 +0800 Subject: [PATCH] refactor(core): reuse computeNewContent in performAddMemoryEntry (#6689) Co-authored-by: chen893 Co-authored-by: Sandy Tao --- packages/core/src/tools/memoryTool.ts | 41 ++++----------------------- 1 file changed, 5 insertions(+), 36 deletions(-) diff --git a/packages/core/src/tools/memoryTool.ts b/packages/core/src/tools/memoryTool.ts index 9d8a070c4a..85e42c0793 100644 --- a/packages/core/src/tools/memoryTool.ts +++ b/packages/core/src/tools/memoryTool.ts @@ -330,49 +330,18 @@ export class MemoryTool ) => Promise; }, ): Promise { - let processedText = text.trim(); - // Remove leading hyphens and spaces that might be misinterpreted as markdown list items - processedText = processedText.replace(/^(-+\s*)+/, '').trim(); - const newMemoryItem = `- ${processedText}`; - try { await fsAdapter.mkdir(path.dirname(memoryFilePath), { recursive: true }); - let content = ''; + let currentContent = ''; try { - content = await fsAdapter.readFile(memoryFilePath, 'utf-8'); + currentContent = await fsAdapter.readFile(memoryFilePath, 'utf-8'); } catch (_e) { - // File doesn't exist, will be created with header and item. + // File doesn't exist, which is fine. currentContent will be empty. } - const headerIndex = content.indexOf(MEMORY_SECTION_HEADER); + const newContent = computeNewContent(currentContent, text); - if (headerIndex === -1) { - // Header not found, append header and then the entry - const separator = ensureNewlineSeparation(content); - content += `${separator}${MEMORY_SECTION_HEADER}\n${newMemoryItem}\n`; - } else { - // Header found, find where to insert the new memory entry - const startOfSectionContent = - headerIndex + MEMORY_SECTION_HEADER.length; - let endOfSectionIndex = content.indexOf('\n## ', startOfSectionContent); - if (endOfSectionIndex === -1) { - endOfSectionIndex = content.length; // End of file - } - - const beforeSectionMarker = content - .substring(0, startOfSectionContent) - .trimEnd(); - let sectionContent = content - .substring(startOfSectionContent, endOfSectionIndex) - .trimEnd(); - const afterSectionMarker = content.substring(endOfSectionIndex); - - sectionContent += `\n${newMemoryItem}`; - content = - `${beforeSectionMarker}\n${sectionContent.trimStart()}\n${afterSectionMarker}`.trimEnd() + - '\n'; - } - await fsAdapter.writeFile(memoryFilePath, content, 'utf-8'); + await fsAdapter.writeFile(memoryFilePath, newContent, 'utf-8'); } catch (error) { console.error( `[MemoryTool] Error adding memory entry to ${memoryFilePath}:`,