Implement inverse edge existence check and enhance edge creation logic
Node.js build / build (20.x) (push) Has been cancelled
Node.js build / build (22.x) (push) Has been cancelled

- Added `checkInverseEdgeExists` function to verify if an inverse edge already exists between two nodes, preventing duplicate edges from being created.
- Updated `createInverseEdge` to utilize the new check, ensuring that inverse edges are only created when necessary.
- Enhanced logging for better traceability during edge creation and existence checks, improving overall debugging capabilities.
- Introduced a new function `getInverseEdgeType` to retrieve the inverse edge type from the vocabulary, supporting the new functionality.
This commit is contained in:
Lars committed 2026-02-06 13:02:33 +01:00
1 parent 99c77ef616
commit 7627a05af4
3 files changed
+323 -27

No files matched your search

+101 -3
View File
@@ -427,6 +427,20 @@ function normalizePathForComparison(path: string): string {
* Uses resolved paths and headingsMatch for heading comparison (block-id variants).
* Paths are normalized so different slash styles (e.g. Windows) still match.
*/
/**
* Get inverse edge type for a canonical type from edge vocabulary.
*/
function getInverseEdgeType(
canonical: string | undefined,
edgeVocabulary: EdgeVocabulary | null
): string | null {
if (!canonical || !edgeVocabulary) {
return null;
}
const entry = edgeVocabulary.byCanonical.get(canonical);
return entry?.inverse ?? null;
}
function findEdgeBetween(
fromKey: string,
toKey: string,
@@ -446,6 +460,7 @@ function findEdgeBetween(
// This prevents early return when a different edge type matches first
const hasAllowedRoles = allowedEdgeRoles && allowedEdgeRoles.length > 0;
// First, try to find edge in forward direction (from→to)
for (const edge of allEdges) {
const sourceFile = "sectionHeading" in edge.source ? edge.source.file : edge.source.file;
const resolvedSourceFile = sourceFile.includes("/") || sourceFile.endsWith(".md")
@@ -481,9 +496,6 @@ function findEdgeBetween(
const canonical = canonicalEdgeType(edge.rawEdgeType);
const edgeRole = getEdgeRole(edge.rawEdgeType, canonical, chainRoles);
// Debug logging for guides edges (only via logger, controlled by log level)
// Removed console.log - use getTemplateMatchingLogger().debug() if needed
// CRITICAL FIX: If allowedEdgeRoles is specified, only return if this edge's role matches
// This prevents early return when a different edge type matches first.
// This fixes the issue where edges later in the list (e.g., guides at index 12) were
@@ -505,6 +517,92 @@ function findEdgeBetween(
}
}
// PROBLEM 2 FIX: If no edge found in forward direction, check reverse direction (to→from)
// This handles cases where only a backlink exists (inverse edge)
// A chain should be considered complete if the semantic relationship exists in either direction
for (const edge of allEdges) {
const sourceFile = "sectionHeading" in edge.source ? edge.source.file : edge.source.file;
const resolvedSourceFile = sourceFile.includes("/") || sourceFile.endsWith(".md")
? sourceFile
: edgeTargetResolutionMap.get(sourceFile) || sourceFile;
let resolvedTargetFile = edgeTargetResolutionMap.get(edge.target.file);
if (!resolvedTargetFile) {
if (!edge.target.file.includes("/") && !edge.target.file.endsWith(".md")) {
const sourceBasename = resolvedSourceFile.split("/").pop()?.replace(/\.md$/, "") || "";
if (sourceBasename === edge.target.file || resolvedSourceFile.endsWith(edge.target.file)) {
resolvedTargetFile = resolvedSourceFile;
}
}
if (!resolvedTargetFile) {
resolvedTargetFile = edge.target.file;
}
}
const resolvedSourceNorm = normalizePathForComparison(resolvedSourceFile);
const resolvedTargetNorm = normalizePathForComparison(resolvedTargetFile);
const sourceHeading = "sectionHeading" in edge.source ? edge.source.sectionHeading : null;
const targetHeading = edge.target.heading;
// Check reverse direction: edge goes from to→from (inverse of what we're looking for)
if (
resolvedSourceNorm === toFileNorm &&
headingsMatch(sourceHeading, toHeading) &&
resolvedTargetNorm === fromFileNorm &&
headingsMatch(targetHeading, fromHeading)
) {
// This is a reverse edge - check if it's the inverse of an allowed edge type
const canonical = canonicalEdgeType(edge.rawEdgeType);
// If we have allowedEdgeRoles, we need to check if this inverse edge's role matches
// For inverse edges, we need to find the forward canonical type and check its role
if (hasAllowedRoles && allowedEdgeRoles.length > 0) {
// For each allowed role, check if this inverse edge's canonical type is the inverse
// of a canonical type that has that role
let matchedRole: string | null = null;
if (chainRoles && canonical) {
// Check if this canonical type (which is the inverse) corresponds to a forward type
// that has one of the allowed roles
for (const [roleName, role] of Object.entries(chainRoles.roles)) {
if (allowedEdgeRoles.includes(roleName)) {
// Check if any edge type in this role has an inverse that matches our edge
for (const forwardType of role.edge_types) {
const forwardCanonical = canonicalEdgeType(forwardType);
if (forwardCanonical) {
const inverseOfForward = getInverseEdgeType(forwardCanonical, edgeVocabulary);
if (inverseOfForward === canonical) {
// This inverse edge corresponds to a forward edge with the allowed role!
matchedRole = roleName;
break;
}
}
}
if (matchedRole) break;
}
}
}
if (matchedRole) {
// Return the inverse edge, but indicate it's in reverse direction
// The role is the forward role (e.g., "guides" for a "guided_by" edge)
return { edgeRole: matchedRole, rawEdgeType: edge.rawEdgeType };
}
// Continue searching
continue;
}
// No allowed roles restriction: if we found a reverse edge, it means the relationship exists
// Return it with the inferred role (if possible)
const edgeRole = canonical && chainRoles ? getEdgeRole(edge.rawEdgeType, canonical, chainRoles) : null;
// Try to infer role from the inverse edge type
const inferredRole = edgeRole || (chainRoles ? inferRoleFromRawType(edge.rawEdgeType, chainRoles) : null);
// For inverse edges, we might need to map the role back to the forward role
// But for now, return the edge as-is - the relationship exists in reverse direction
return { edgeRole: inferredRole, rawEdgeType: edge.rawEdgeType };
}
}
return null;
}