Skip to content

Commit abbbddb

Browse files
authored
fix(memory): stop reporting deletions that did not happen (#4738)
delete_entities, delete_observations and delete_relations returned success: true with a hardcoded "deleted successfully" message regardless of what matched. An agent that mistypes an entity name is told its memory is clean while the data is still on disk, and nothing in the response contradicts that. addObservations throws for the same condition ten lines above, so the file already disagreed with itself. Staying quiet is deliberate and documented, so nothing throws and the output schema is unchanged. The three manager methods now return what they matched, and the handlers say so. A delete where everything is found returns the same message it always did. README updated: the three "Silent operation" bullets described the absence of an error, which is still true, but read as if the response said nothing either.
1 parent 649af58 commit abbbddb

3 files changed

Lines changed: 138 additions & 15 deletions

File tree

‎src/memory/README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,15 +87,15 @@ Example:
8787
- Remove entities and their relations
8888
- Input: `entityNames` (string[])
8989
- Cascading deletion of associated relations
90-
- Silent operation if entity doesn't exist
90+
- No error if an entity doesn't exist; the response reports which names were not found
9191

9292
- **delete_observations**
9393
- Remove specific observations from entities
9494
- Input: `deletions` (array of objects)
9595
- Each object contains:
9696
- `entityName` (string): Target entity
9797
- `observations` (string[]): Observations to remove
98-
- Silent operation if observation doesn't exist
98+
- No error if an observation doesn't exist; the response reports how many were deleted
9999

100100
- **delete_relations**
101101
- Remove specific relations from the graph
@@ -104,7 +104,7 @@ Example:
104104
- `from` (string): Source entity name
105105
- `to` (string): Target entity name
106106
- `relationType` (string): Relationship type
107-
- Silent operation if relation doesn't exist
107+
- No error if a relation doesn't exist; the response reports how many were deleted
108108

109109
- **read_graph**
110110
- Read the entire knowledge graph
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2+
import { promises as fs } from 'fs';
3+
import path from 'path';
4+
import { fileURLToPath } from 'url';
5+
import { KnowledgeGraphManager, Entity, Relation } from '../index.js';
6+
7+
/**
8+
* The delete tools stay silent when a target is absent, which the README
9+
* documents. What they must not do is report a deletion that did not happen:
10+
* an agent that mistypes a name is told its memory is clean while the data is
11+
* still on disk, and nothing in the response contradicts that.
12+
*/
13+
describe('delete reporting', () => {
14+
let manager: KnowledgeGraphManager;
15+
let testFilePath: string;
16+
17+
const entities: Entity[] = [
18+
{ name: 'Alice', entityType: 'person', observations: ['works at Acme Corp', 'likes tea'] },
19+
{ name: 'Bob', entityType: 'person', observations: ['likes programming'] },
20+
];
21+
const relations: Relation[] = [{ from: 'Alice', to: 'Bob', relationType: 'works_with' }];
22+
23+
beforeEach(async () => {
24+
testFilePath = path.join(
25+
path.dirname(fileURLToPath(import.meta.url)),
26+
`test-delete-reporting-${Date.now()}-${Math.random().toString(16).slice(2)}.jsonl`
27+
);
28+
manager = new KnowledgeGraphManager(testFilePath);
29+
await manager.createEntities(entities);
30+
await manager.createRelations(relations);
31+
});
32+
33+
afterEach(async () => {
34+
try {
35+
await fs.unlink(testFilePath);
36+
} catch {
37+
// the file is gone already
38+
}
39+
});
40+
41+
describe('deleteEntities', () => {
42+
it('reports which names matched and which did not', async () => {
43+
const result = await manager.deleteEntities(['Alice', 'Alise']);
44+
expect(result).toEqual({ deleted: ['Alice'], notFound: ['Alise'] });
45+
});
46+
47+
it('reports nothing deleted when no name matches', async () => {
48+
const result = await manager.deleteEntities(['Nobody']);
49+
expect(result).toEqual({ deleted: [], notFound: ['Nobody'] });
50+
51+
const graph = await manager.readGraph();
52+
expect(graph.entities).toHaveLength(2);
53+
});
54+
55+
it('still deletes the entity and its relations', async () => {
56+
await manager.deleteEntities(['Alice']);
57+
58+
const graph = await manager.readGraph();
59+
expect(graph.entities.map(e => e.name)).toEqual(['Bob']);
60+
expect(graph.relations).toHaveLength(0);
61+
});
62+
});
63+
64+
describe('deleteObservations', () => {
65+
it('counts only the observations that were present', async () => {
66+
const result = await manager.deleteObservations([
67+
{ entityName: 'Alice', observations: ['likes tea', 'never said this'] },
68+
]);
69+
expect(result).toEqual({ deletedCount: 1, missingEntities: [] });
70+
});
71+
72+
it('names an entity that does not exist', async () => {
73+
const result = await manager.deleteObservations([
74+
{ entityName: 'Carol', observations: ['anything'] },
75+
]);
76+
expect(result).toEqual({ deletedCount: 0, missingEntities: ['Carol'] });
77+
});
78+
});
79+
80+
describe('deleteRelations', () => {
81+
it('counts only the relations that matched', async () => {
82+
const result = await manager.deleteRelations([
83+
{ from: 'Alice', to: 'Bob', relationType: 'works_with' },
84+
{ from: 'Alice', to: 'Bob', relationType: 'never_existed' },
85+
]);
86+
expect(result).toEqual({ deletedCount: 1 });
87+
});
88+
89+
it('reports nothing deleted when the relation type is wrong', async () => {
90+
const result = await manager.deleteRelations([
91+
{ from: 'Alice', to: 'Bob', relationType: 'manages' },
92+
]);
93+
expect(result).toEqual({ deletedCount: 0 });
94+
95+
const graph = await manager.readGraph();
96+
expect(graph.relations).toHaveLength(1);
97+
});
98+
});
99+
});

‎src/memory/index.ts‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -202,32 +202,45 @@ export class KnowledgeGraphManager {
202202
return results;
203203
}
204204

205-
async deleteEntities(entityNames: string[]): Promise<void> {
205+
async deleteEntities(entityNames: string[]): Promise<{ deleted: string[]; notFound: string[] }> {
206206
const graph = await this.loadGraph();
207+
const present = new Set(graph.entities.map(e => e.name));
208+
const deleted = entityNames.filter(name => present.has(name));
209+
const notFound = entityNames.filter(name => !present.has(name));
207210
graph.entities = graph.entities.filter(e => !entityNames.includes(e.name));
208211
graph.relations = graph.relations.filter(r => !entityNames.includes(r.from) && !entityNames.includes(r.to));
209212
await this.saveGraph(graph);
213+
return { deleted, notFound };
210214
}
211215

212-
async deleteObservations(deletions: { entityName: string; observations: string[] }[]): Promise<void> {
216+
async deleteObservations(deletions: { entityName: string; observations: string[] }[]): Promise<{ deletedCount: number; missingEntities: string[] }> {
213217
const graph = await this.loadGraph();
218+
let deletedCount = 0;
219+
const missingEntities: string[] = [];
214220
deletions.forEach(d => {
215221
const entity = graph.entities.find(e => e.name === d.entityName);
216222
if (entity) {
223+
const before = entity.observations.length;
217224
entity.observations = entity.observations.filter(o => !d.observations.includes(o));
225+
deletedCount += before - entity.observations.length;
226+
} else {
227+
missingEntities.push(d.entityName);
218228
}
219229
});
220230
await this.saveGraph(graph);
231+
return { deletedCount, missingEntities };
221232
}
222233

223-
async deleteRelations(relations: Relation[]): Promise<void> {
234+
async deleteRelations(relations: Relation[]): Promise<{ deletedCount: number }> {
224235
const graph = await this.loadGraph();
236+
const before = graph.relations.length;
225237
graph.relations = graph.relations.filter(r => !relations.some(delRelation =>
226238
r.from === delRelation.from &&
227239
r.to === delRelation.to &&
228240
r.relationType === delRelation.relationType
229241
));
230242
await this.saveGraph(graph);
243+
return { deletedCount: before - graph.relations.length };
231244
}
232245

233246
async readGraph(): Promise<KnowledgeGraph> {
@@ -436,11 +449,14 @@ server.registerTool(
436449
}
437450
},
438451
async ({ entityNames }) => {
439-
await knowledgeGraphManager.deleteEntities(entityNames);
452+
const { deleted, notFound } = await knowledgeGraphManager.deleteEntities(entityNames);
440453
notifyGraphUpdated();
454+
const message = notFound.length === 0
455+
? "Entities deleted successfully"
456+
: `Deleted ${deleted.length} of ${entityNames.length} entities. Not found: ${notFound.join(", ")}`;
441457
return {
442-
content: [{ type: "text" as const, text: "Entities deleted successfully" }],
443-
structuredContent: { success: true, message: "Entities deleted successfully" }
458+
content: [{ type: "text" as const, text: message }],
459+
structuredContent: { success: true, message }
444460
};
445461
}
446462
);
@@ -469,11 +485,16 @@ server.registerTool(
469485
}
470486
},
471487
async ({ deletions }) => {
472-
await knowledgeGraphManager.deleteObservations(deletions);
488+
const { deletedCount, missingEntities } = await knowledgeGraphManager.deleteObservations(deletions);
473489
notifyGraphUpdated();
490+
const requested = deletions.reduce((total, d) => total + d.observations.length, 0);
491+
const message = deletedCount === requested
492+
? "Observations deleted successfully"
493+
: `Deleted ${deletedCount} of ${requested} observations.` +
494+
(missingEntities.length ? ` Entities not found: ${missingEntities.join(", ")}` : "");
474495
return {
475-
content: [{ type: "text" as const, text: "Observations deleted successfully" }],
476-
structuredContent: { success: true, message: "Observations deleted successfully" }
496+
content: [{ type: "text" as const, text: message }],
497+
structuredContent: { success: true, message }
477498
};
478499
}
479500
);
@@ -499,11 +520,14 @@ server.registerTool(
499520
}
500521
},
501522
async ({ relations }) => {
502-
await knowledgeGraphManager.deleteRelations(relations);
523+
const { deletedCount } = await knowledgeGraphManager.deleteRelations(relations);
503524
notifyGraphUpdated();
525+
const message = deletedCount === relations.length
526+
? "Relations deleted successfully"
527+
: `Deleted ${deletedCount} of ${relations.length} relations. The rest matched nothing.`;
504528
return {
505-
content: [{ type: "text" as const, text: "Relations deleted successfully" }],
506-
structuredContent: { success: true, message: "Relations deleted successfully" }
529+
content: [{ type: "text" as const, text: message }],
530+
structuredContent: { success: true, message }
507531
};
508532
}
509533
);

0 commit comments

Comments
 (0)