(
text: string,
memoryFilePath: string,
fsAdapter: {
readFile: (path: string, encoding: 'utf-8') => Promise<string>;
writeFile: (
path: string,
data: string,
encoding: 'utf-8',
) => Promise<void>;
mkdir: (
path: string,
options: { recursive: boolean },
) => Promise<string | undefined>;
},
)
| 345 | } |
| 346 | |
| 347 | static async performAddMemoryEntry( |
| 348 | text: string, |
| 349 | memoryFilePath: string, |
| 350 | fsAdapter: { |
| 351 | readFile: (path: string, encoding: 'utf-8') => Promise<string>; |
| 352 | writeFile: ( |
| 353 | path: string, |
| 354 | data: string, |
| 355 | encoding: 'utf-8', |
| 356 | ) => Promise<void>; |
| 357 | mkdir: ( |
| 358 | path: string, |
| 359 | options: { recursive: boolean }, |
| 360 | ) => Promise<string | undefined>; |
| 361 | }, |
| 362 | ): Promise<void> { |
| 363 | let processedText = text.trim(); |
| 364 | // Remove leading hyphens and spaces that might be misinterpreted as markdown list items |
| 365 | processedText = processedText.replace(/^(-+\s*)+/, '').trim(); |
| 366 | const newMemoryItem = `- ${processedText}`; |
| 367 | |
| 368 | try { |
| 369 | await fsAdapter.mkdir(path.dirname(memoryFilePath), { recursive: true }); |
| 370 | let content = ''; |
| 371 | try { |
| 372 | content = await fsAdapter.readFile(memoryFilePath, 'utf-8'); |
| 373 | } catch (_e) { |
| 374 | // File doesn't exist, will be created with header and item. |
| 375 | } |
| 376 | |
| 377 | const headerIndex = content.indexOf(MEMORY_SECTION_HEADER); |
| 378 | |
| 379 | if (headerIndex === -1) { |
| 380 | // Header not found, append header and then the entry |
| 381 | const separator = ensureNewlineSeparation(content); |
| 382 | content += `${separator}${MEMORY_SECTION_HEADER}\n${newMemoryItem}\n`; |
| 383 | } else { |
| 384 | // Header found, find where to insert the new memory entry |
| 385 | const startOfSectionContent = |
| 386 | headerIndex + MEMORY_SECTION_HEADER.length; |
| 387 | let endOfSectionIndex = content.indexOf('\n## ', startOfSectionContent); |
| 388 | if (endOfSectionIndex === -1) { |
| 389 | endOfSectionIndex = content.length; // End of file |
| 390 | } |
| 391 | |
| 392 | const beforeSectionMarker = content |
| 393 | .substring(0, startOfSectionContent) |
| 394 | .trimEnd(); |
| 395 | let sectionContent = content |
| 396 | .substring(startOfSectionContent, endOfSectionIndex) |
| 397 | .trimEnd(); |
| 398 | const afterSectionMarker = content.substring(endOfSectionIndex); |
| 399 | |
| 400 | sectionContent += `\n${newMemoryItem}`; |
| 401 | content = |
| 402 | `${beforeSectionMarker}\n${sectionContent.trimStart()}\n${afterSectionMarker}`.trimEnd() + |
| 403 | '\n'; |
| 404 | } |
no test coverage detected