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
10 changes: 10 additions & 0 deletions src/memory/__tests__/knowledge-graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ describe('KnowledgeGraphManager', () => {
const newEntities = await manager.createEntities([]);
expect(newEntities).toHaveLength(0);
});

it('should persist graph snapshots without leaving temporary files', async () => {
await manager.createEntities([
{ name: 'Atomic', entityType: 'test', observations: ['durable'] },
]);

const files = await fs.readdir(path.dirname(testFilePath));
expect(files.filter(file => file.startsWith(path.basename(testFilePath) + '.') && file.endsWith('.tmp'))).toEqual([]);
await expect(fs.readFile(testFilePath, 'utf-8')).resolves.toContain('Atomic');
});
});

describe('createRelations', () => {
Expand Down
18 changes: 17 additions & 1 deletion src/memory/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { z } from "zod";
import { promises as fs } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { randomUUID } from 'crypto';

// Define memory file path using environment variable with fallback
export const defaultMemoryPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'memory.jsonl');
Expand Down Expand Up @@ -114,7 +115,22 @@ export class KnowledgeGraphManager {
relationType: r.relationType
})),
];
await fs.writeFile(this.memoryFilePath, lines.join("\n"));
// Write the complete snapshot away from the live file, then atomically
// replace it. A direct writeFile truncates memory.jsonl first, so a process
// interruption can leave the graph permanently partial or unreadable.
const temporaryPath = `${this.memoryFilePath}.${process.pid}.${randomUUID()}.tmp`;
try {
await fs.writeFile(temporaryPath, lines.join("\n"));
await fs.rename(temporaryPath, this.memoryFilePath);
} finally {
try {
await fs.unlink(temporaryPath);
} catch (error) {
if (!(error instanceof Error && 'code' in error && (error as any).code === 'ENOENT')) {
throw error;
}
}
}
}

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