feat(kg): bidirectional multi-hop traversal

Add reverse-edge UNION ALL to recursive CTE so traversal follows both
source→target and target→source edges. Reverse edges prefixed with ~
in via field (e.g. ~manages). Tool output shows directional arrows.
This commit is contained in:
viettranx committed 2026-03-31 17:55:27 +07:00
1 parent 9ad4a879d5
commit b99f119e37
2 files changed
+37 -1

No files matched your search

@@ -68,6 +68,22 @@ func (s *PGKnowledgeGraphStore) Traverse(ctx context.Context, agentID, userID, s
JOIN kg_entities e ON r.target_entity_id = e.id AND e.agent_id = $2
WHERE p.depth < $%d
AND NOT e.id::text = ANY(p.path)
UNION ALL
SELECT
e.id, e.agent_id, e.user_id, e.external_id,
e.name, e.entity_type, e.description,
e.properties, e.source_id, e.confidence,
e.created_at, e.updated_at,
p.depth + 1,
p.path || e.id::text,
'~' || r.relation_type
FROM paths p
JOIN kg_relations r ON p.id = r.target_entity_id AND r.agent_id = $2
JOIN kg_entities e ON r.source_entity_id = e.id AND e.agent_id = $2
WHERE p.depth < $%[2]d
AND NOT e.id::text = ANY(p.path)
)
SELECT
id, agent_id, user_id, external_id,
@@ -113,6 +129,22 @@ func (s *PGKnowledgeGraphStore) Traverse(ctx context.Context, agentID, userID, s
JOIN kg_entities e ON r.target_entity_id = e.id AND e.user_id = $3
WHERE p.depth < $%d
AND NOT e.id::text = ANY(p.path)
UNION ALL
SELECT
e.id, e.agent_id, e.user_id, e.external_id,
e.name, e.entity_type, e.description,
e.properties, e.source_id, e.confidence,
e.created_at, e.updated_at,
p.depth + 1,
p.path || e.id::text,
'~' || r.relation_type
FROM paths p
JOIN kg_relations r ON p.id = r.target_entity_id AND r.user_id = $3
JOIN kg_entities e ON r.source_entity_id = e.id AND e.user_id = $3
WHERE p.depth < $%[2]d
AND NOT e.id::text = ANY(p.path)
)
SELECT
id, agent_id, user_id, external_id,
+5 -1
View File
@@ -110,7 +110,11 @@ func (t *KnowledgeGraphSearchTool) executeTraversal(ctx context.Context, agentID
for _, r := range results {
sb.WriteString(fmt.Sprintf("- [depth %d] %s (%s)", r.Depth, r.Entity.Name, r.Entity.EntityType))
if r.Via != "" {
sb.WriteString(fmt.Sprintf(" via %q", r.Via))
if strings.HasPrefix(r.Via, "~") {
sb.WriteString(fmt.Sprintf(" ←[%s]—", r.Via[1:]))
} else {
sb.WriteString(fmt.Sprintf(" —[%s]→", r.Via))
}
}
if r.Entity.Description != "" {
sb.WriteString(fmt.Sprintf("\n %s", r.Entity.Description))