Skip to content
Open
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
1 change: 1 addition & 0 deletions src/memory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ Example:
- `to` (string): Target entity name
- `relationType` (string): Relationship type in active voice
- Skips duplicate relations
- Fails if either the source or target entity doesn't exist

- **add_observations**
- Add new observations to existing entities
Expand Down
32 changes: 32 additions & 0 deletions src/memory/__tests__/knowledge-graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,38 @@ describe('KnowledgeGraphManager', () => {
expect(graph.relations).toHaveLength(1);
});

it('should reject relations from non-existent entities', async () => {
await manager.createEntities([
{ name: 'Alice', entityType: 'person', observations: [] },
]);

await expect(
manager.createRelations([
{ from: 'Ghost', to: 'Alice', relationType: 'knows' },
])
).rejects.toThrow('Entity with name Ghost not found');

const graph = await manager.readGraph();
expect(graph.relations).toHaveLength(0);
});

it('should reject relation batches that reference non-existent target entities', async () => {
await manager.createEntities([
{ name: 'Alice', entityType: 'person', observations: [] },
{ name: 'Bob', entityType: 'person', observations: [] },
]);

await expect(
manager.createRelations([
{ from: 'Alice', to: 'Bob', relationType: 'knows' },
{ from: 'Alice', to: 'Ghost', relationType: 'knows' },
])
).rejects.toThrow('Entity with name Ghost not found');

const graph = await manager.readGraph();
expect(graph.relations).toHaveLength(0);
});

it('should handle empty relation arrays', async () => {
const newRelations = await manager.createRelations([]);
expect(newRelations).toHaveLength(0);
Expand Down
11 changes: 11 additions & 0 deletions src/memory/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,17 @@ export class KnowledgeGraphManager {

async createRelations(relations: Relation[]): Promise<Relation[]> {
const graph = await this.loadGraph();
const entityNames = new Set(graph.entities.map(e => e.name));

relations.forEach(r => {
if (!entityNames.has(r.from)) {
throw new Error(`Entity with name ${r.from} not found`);
}
if (!entityNames.has(r.to)) {
throw new Error(`Entity with name ${r.to} not found`);
}
});

const newRelations = relations.filter(r => !graph.relations.some(existingRelation =>
existingRelation.from === r.from &&
existingRelation.to === r.to &&
Expand Down
Loading