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
29 changes: 21 additions & 8 deletions src/functions/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,19 +423,23 @@ function parseGraphXml(
addEntity(match[1], match[2]);
}

const relRegex = /<relationship\b([^>]*?)\/>/g;
while ((match = relRegex.exec(xml)) !== null) {
const attrs = parseAttrs(match[1]);
const nodeByNormName = new Map<string, GraphNode>();
for (const n of nodes) {
const key = n.name.trim().toLowerCase();
if (!nodeByNormName.has(key)) nodeByNormName.set(key, n);
}

const addRelationship = (rawAttrs: string): void => {
const attrs = parseAttrs(rawAttrs);
const type = attrs["type"] as GraphEdge["type"] | undefined;
const sourceName = attrs["source"];
const targetName = attrs["target"];
if (!type || !sourceName || !targetName) continue;
if (!type || !sourceName || !targetName) return;
const sourceNode = nodeByNormName.get(sourceName.trim().toLowerCase());
const targetNode = nodeByNormName.get(targetName.trim().toLowerCase());
if (!sourceNode || !targetNode) return;
const parsedWeight = parseFloat(attrs["weight"] ?? "");
const weight = Number.isFinite(parsedWeight) ? parsedWeight : 0.5;

const sourceNode = nodes.find((n) => n.name === sourceName);
const targetNode = nodes.find((n) => n.name === targetName);
if (!sourceNode || !targetNode) continue;
edges.push({
id: generateId("ge"),
type,
Expand All @@ -445,6 +449,15 @@ function parseGraphXml(
sourceObservationIds: observationIds,
createdAt: now,
});
};

const relSelfClose = /<relationship\b([^>]*?)\/>/g;
while ((match = relSelfClose.exec(xml)) !== null) {
addRelationship(match[1]);
}
const relWithBody = /<relationship\b([^>]*[^/])>[\s\S]*?<\/relationship>/g;
while ((match = relWithBody.exec(xml)) !== null) {
addRelationship(match[1]);
}

return { nodes, edges };
Expand Down
14 changes: 13 additions & 1 deletion src/prompts/graph-extraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,19 @@ Rules:
- Extract concrete entities only (real file paths, function names, library names)
- Use the most specific type available
- Weight relationships by how strong/direct the connection is
- If no entities found, output empty tags`;
- If no entities found, output empty tags
- Every relationship source and target MUST be the exact name of an entity declared in <entities>; never reference an entity you did not declare

Example:
<entities>
<entity type="file" name="src/auth/login.ts"/>
<entity type="function" name="validateToken"/>
<entity type="library" name="jose"/>
</entities>
<relationships>
<relationship type="imports" source="src/auth/login.ts" target="jose" weight="0.9"/>
<relationship type="uses" source="validateToken" target="jose" weight="0.8"/>
</relationships>`;

export function buildGraphExtractionPrompt(
observations: Array<{
Expand Down
13 changes: 13 additions & 0 deletions test/graph-prompt.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { describe, it, expect } from "vitest";

import { GRAPH_EXTRACTION_SYSTEM } from "../src/prompts/graph-extraction.js";

describe("GRAPH_EXTRACTION_SYSTEM prompt", () => {
it("instructs that relationship endpoints must reference a declared entity", () => {
expect(GRAPH_EXTRACTION_SYSTEM).toMatch(/declared/i);
});

it("includes a concrete few-shot example", () => {
expect(GRAPH_EXTRACTION_SYSTEM).toMatch(/Example/i);
});
});
83 changes: 81 additions & 2 deletions test/graph.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";

vi.mock("../src/logger.js", () => ({
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
}));

import { registerGraphFunction } from "../src/functions/graph.js";
import { registerGraphFunction, getGraphExtractTimeoutMs } from "../src/functions/graph.js";
import type {
CompressedObservation,
GraphNode,
Expand Down Expand Up @@ -730,3 +730,82 @@ describe("Graph Functions", () => {
});
});
});


describe("parseGraphXml relation resolution", () => {
let sdk: ReturnType<typeof mockSdk>;
let kv: ReturnType<typeof mockKV>;

beforeEach(() => {
sdk = mockSdk();
kv = mockKV();
vi.clearAllMocks();
mockProvider.compress.mockResolvedValue(
`<entities></entities><relationships></relationships>`,
);
registerGraphFunction(sdk as never, kv as never, mockProvider as never);
});

it("resolves relationship endpoints case-insensitively and trimmed", async () => {
mockProvider.compress.mockResolvedValueOnce(`<entities>
<entity type="concept" name="UserService"/>
<entity type="concept" name="Database"/>
</entities>
<relationships>
<relationship type="uses" source="userservice" target=" Database " weight="0.8"/>
</relationships>`);

const result = (await sdk.trigger("mem::graph-extract", {
observations: [testObs],
})) as { success: boolean; nodesAdded: number; edgesAdded: number };

expect(result.success).toBe(true);
expect(result.nodesAdded).toBe(2);
expect(result.edgesAdded).toBe(1);

const edges = await kv.list<GraphEdge>("mem:graph:edges");
expect(edges).toHaveLength(1);
expect(edges[0].type).toBe("uses");
});

it("accepts body-form <relationship>...</relationship> tags", async () => {
mockProvider.compress.mockResolvedValueOnce(`<entities>
<entity type="file" name="src/a.ts"/>
<entity type="function" name="run"/>
</entities>
<relationships>
<relationship type="uses" source="src/a.ts" target="run" weight="0.7"></relationship>
</relationships>`);

const result = (await sdk.trigger("mem::graph-extract", {
observations: [testObs],
})) as { success: boolean; edgesAdded: number };

expect(result.success).toBe(true);
expect(result.edgesAdded).toBe(1);

const edges = await kv.list<GraphEdge>("mem:graph:edges");
expect(edges).toHaveLength(1);
expect(edges[0].type).toBe("uses");
});

it("drops a relationship whose endpoint is not a declared entity", async () => {
mockProvider.compress.mockResolvedValueOnce(`<entities>
<entity type="concept" name="Declared"/>
</entities>
<relationships>
<relationship type="related_to" source="Declared" target="Undeclared" weight="0.5"/>
</relationships>`);

const result = (await sdk.trigger("mem::graph-extract", {
observations: [testObs],
})) as { success: boolean; nodesAdded: number; edgesAdded: number };

expect(result.success).toBe(true);
expect(result.nodesAdded).toBe(1);
expect(result.edgesAdded).toBe(0);

const edges = await kv.list<GraphEdge>("mem:graph:edges");
expect(edges).toHaveLength(0);
});
});