Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/memory/__tests__/knowledge-graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,4 +515,20 @@ describe('KnowledgeGraphManager', () => {
expect(result.relations[0]).not.toHaveProperty('type');
});
});

describe('atomic saveGraph persistence', () => {
it('should cleanly persist data and leave no leftover temp files', async () => {
await manager.createEntities([
{ name: 'Carol', entityType: 'person', observations: ['software engineer'] },
]);

const dir = path.dirname(testFilePath);
const files = await fs.readdir(dir);
const tempFiles = files.filter(f => f.startsWith(path.basename(testFilePath)) && f.endsWith('.tmp'));
expect(tempFiles).toHaveLength(0);

const content = await fs.readFile(testFilePath, 'utf-8');
expect(content).toContain('Carol');
});
});
});
13 changes: 12 additions & 1 deletion src/memory/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,18 @@ export class KnowledgeGraphManager {
relationType: r.relationType
})),
];
await fs.writeFile(this.memoryFilePath, lines.join("\n"));
const tmpPath = `${this.memoryFilePath}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;
try {
await fs.writeFile(tmpPath, lines.join("\n"));
await fs.rename(tmpPath, this.memoryFilePath);
} catch (error) {
try {
await fs.unlink(tmpPath);
} catch {
// Ignore cleanup error if temp file does not exist
}
throw error;
}
}

async createEntities(entities: Entity[]): Promise<Entity[]> {
Expand Down