Enhance edge parsing and settings for improved template matching
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run

- Updated `parseEdgesFromCallouts.ts` to support edge extraction from both callout blocks and plain lines, allowing for more flexible edge definitions.
- Introduced new settings in `settings.ts` for maximum assignments collected per template, enhancing loop protection during edge processing.
- Enhanced documentation in `Entwicklerhandbuch.md` to reflect changes in edge parsing and settings.
- Improved UI components to utilize the new settings for better user experience in the Chain Workbench and related features.
This commit is contained in:
Lars committed 2026-02-06 11:40:44 +01:00
1 parent ad543248c7
commit e6cd4aafec
38 files changed
+3952 -75

No files matched your search

+6 -4
View File
@@ -27,9 +27,11 @@ export interface InspectorOptions {
includeCandidates: boolean;
maxDepth: number;
direction: "forward" | "backward" | "both";
maxTemplateMatches?: number; // Optional: limit number of template matches (default: 3)
maxTemplateMatches?: number; // Optional: limit per template; undefined = no limit (e.g. Chain Workbench)
/** Default max distinct matches per template. Overridable by chain_templates.yaml defaults.matching.max_matches_per_template. */
maxMatchesPerTemplateDefault?: number; // default: 2
/** Schleifenschutz: max. gesammelte Zuordnungen pro Template. Overridable durch chain_templates.yaml defaults.matching.max_assignments_collected. */
maxAssignmentsCollectedDefault?: number; // default: 1000
/** When true, log template-matching details (candidates per slot, collected/complete counts, returned matches) to console. */
debugLogging?: boolean;
}
@@ -1066,8 +1068,8 @@ export async function inspectChains(
return a.templateName.localeCompare(b.templateName);
});
// Limit to topN per template (default: 3), so up to N chains per chain type, not N total
const topN = options.maxTemplateMatches ?? 3;
// Limit to topN per template when maxTemplateMatches is set; undefined = no limit (e.g. Chain Workbench)
const topN = options.maxTemplateMatches !== undefined ? options.maxTemplateMatches : Number.MAX_SAFE_INTEGER;
const byTemplate = new Map<string, typeof allTemplateMatches>();
for (const m of sortedMatches) {
const list = byTemplate.get(m.templateName) ?? [];
@@ -1076,7 +1078,7 @@ export async function inspectChains(
}
templateMatches = [];
for (const list of byTemplate.values()) {
templateMatches.push(...list.slice(0, topN));
templateMatches.push(...(topN < Number.MAX_SAFE_INTEGER ? list.slice(0, topN) : list));
}
templateMatches.sort((a, b) => {
const rankDiff = confidenceRank(b.confidence) - confidenceRank(a.confidence);
+195 -32
View File
@@ -166,8 +166,11 @@ function normalizeTemplate(
/**
* Build candidate node set from edges.
*
* Hinweis: Diese Funktion wird in Tests (debugCandidateNodes) direkt verwendet,
* daher ist sie explizit exportiert.
*/
async function buildCandidateNodes(
export async function buildCandidateNodes(
app: App,
currentContext: { file: string; heading: string | null },
allEdges: IndexedEdge[],
@@ -180,25 +183,65 @@ async function buildCandidateNodes(
// Normalize heading so "Ergebnis & Auswirkung" and "Ergebnis & Auswirkung ^impact" become one key (one candidate per section)
const norm = (h: string | null | undefined) => normalizeHeadingForMatch(h ?? null) ?? "";
// CRITICAL: Pre-resolve file paths for edges to ensure consistent keys
// This prevents duplicate candidate nodes when edges use different path formats (e.g., "file.md" vs "folder/file.md")
const fileResolutionCache = new Map<string, string>();
const resolveFileForKey = (file: string, sourceFile?: string): string => {
if (fileResolutionCache.has(file)) {
return fileResolutionCache.get(file)!;
}
// If file already has path, use it
if (file.includes("/") || file.endsWith(".md")) {
const fileObj = app.vault.getAbstractFileByPath(file);
if (fileObj && "path" in fileObj) {
fileResolutionCache.set(file, fileObj.path);
return fileObj.path;
}
}
// Try to resolve as wikilink
if (sourceFile) {
const resolved = app.metadataCache.getFirstLinkpathDest(file, sourceFile);
if (resolved) {
fileResolutionCache.set(file, resolved.path);
return resolved.path;
}
}
// Check if it matches source file basename (intra-note link)
if (sourceFile) {
const sourceBasename = sourceFile.split("/").pop()?.replace(/\.md$/, "") || "";
if (sourceBasename === file) {
fileResolutionCache.set(file, sourceFile);
return sourceFile;
}
}
// Fallback: use original
fileResolutionCache.set(file, file);
return file;
};
// Add current context node
const currentKey = `${currentContext.file}:${norm(currentContext.heading)}`;
nodeKeys.add(currentKey);
// Add all target nodes from edges
// Add all target nodes from edges (with resolved file paths)
for (const edge of allEdges) {
if (edge.scope === "candidate" && !options.includeCandidates) continue;
if (edge.scope === "note" && !options.includeNoteLinks) continue;
const targetKey = `${edge.target.file}:${norm(edge.target.heading)}`;
// Resolve target file path before creating key
const sourceFile = "sectionHeading" in edge.source ? edge.source.file : edge.source.file;
const resolvedTargetFile = resolveFileForKey(edge.target.file, sourceFile);
const targetKey = `${resolvedTargetFile}:${norm(edge.target.heading)}`;
nodeKeys.add(targetKey);
// Add source nodes (for incoming edges)
// Note: Source files should already be full paths from graphIndex
// Note: Source files should already be full paths from graphIndex, but resolve to be sure
const resolvedSourceFile = resolveFileForKey(sourceFile, currentContext.file);
if ("sectionHeading" in edge.source) {
const sourceKey = `${edge.source.file}:${norm(edge.source.sectionHeading)}`;
const sourceKey = `${resolvedSourceFile}:${norm(edge.source.sectionHeading)}`;
nodeKeys.add(sourceKey);
} else {
const sourceKey = `${edge.source.file}:`;
const sourceKey = `${resolvedSourceFile}:`;
nodeKeys.add(sourceKey);
}
}
@@ -391,19 +434,38 @@ function findEdgeBetween(
canonicalEdgeType: (rawType: string) => string | undefined,
chainRoles: ChainRolesConfig | null,
edgeVocabulary: EdgeVocabulary | null,
edgeTargetResolutionMap: Map<string, string>
edgeTargetResolutionMap: Map<string, string>,
allowedEdgeRoles?: string[] | null
): { edgeRole: string | null; rawEdgeType: string } | null {
const { file: fromFile, heading: fromHeading } = parseNodeKey(fromKey);
const { file: toFile, heading: toHeading } = parseNodeKey(toKey);
const fromFileNorm = normalizePathForComparison(fromFile);
const toFileNorm = normalizePathForComparison(toFile);
// If allowedEdgeRoles is specified, we need to find an edge with one of those roles
// This prevents early return when a different edge type matches first
const hasAllowedRoles = allowedEdgeRoles && allowedEdgeRoles.length > 0;
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;
const resolvedTargetFile = edgeTargetResolutionMap.get(edge.target.file) || edge.target.file;
// CRITICAL FIX: If target file is not in map and doesn't have path, try resolving it
let resolvedTargetFile = edgeTargetResolutionMap.get(edge.target.file);
if (!resolvedTargetFile) {
// If target file looks like a basename (no /, no .md), and source file is known,
// check if it matches source file basename (intra-note link)
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; // Same file!
}
}
if (!resolvedTargetFile) {
resolvedTargetFile = edge.target.file; // Fallback
}
}
const resolvedSourceNorm = normalizePathForComparison(resolvedSourceFile);
const resolvedTargetNorm = normalizePathForComparison(resolvedTargetFile);
@@ -418,6 +480,29 @@ function findEdgeBetween(
) {
const canonical = canonicalEdgeType(edge.rawEdgeType);
const edgeRole = getEdgeRole(edge.rawEdgeType, canonical, chainRoles);
// Debug logging for guides edges
if (hasAllowedRoles && edge.rawEdgeType === "guides") {
console.log(`[findEdgeBetween] Checking guides edge: rawEdgeType=${edge.rawEdgeType}, canonical=${canonical}, edgeRole=${edgeRole}, chainRoles=${chainRoles ? "set" : "null"}`);
}
// 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
// skipped because an earlier edge (e.g., foundation_for at index 11) matched first.
if (hasAllowedRoles) {
// If edgeRole is null, try to infer it using inferRoleFromRawType
// This handles cases where getEdgeRole returns null but the edge type is still valid
const finalEdgeRole = edgeRole || (chainRoles ? inferRoleFromRawType(edge.rawEdgeType, chainRoles) : null);
if (finalEdgeRole && allowedEdgeRoles.includes(finalEdgeRole)) {
return { edgeRole: finalEdgeRole, rawEdgeType: edge.rawEdgeType };
}
// Continue searching for an edge with an allowed role
continue;
}
// No allowed roles restriction: return first match
return { edgeRole, rawEdgeType: edge.rawEdgeType };
}
}
@@ -553,6 +638,12 @@ function scoreAssignment(
const fromKey = `${fromNode.nodeKey.file}:${fromNode.nodeKey.heading || ""}`;
const toKey = `${toNode.nodeKey.file}:${toNode.nodeKey.heading || ""}`;
// Enhanced debug for guides edge
const isGuidesDebugLink = link.from === "learning" && link.to === "next";
if (isGuidesDebugLink || debugLogging) {
getTemplateMatchingLogger().debug(`[scoreAssignment] Before findEdgeBetween: fromKey=${fromKey}, toKey=${toKey}, fromNode.file=${fromNode.nodeKey.file}, fromNode.heading=${fromNode.nodeKey.heading}, toNode.file=${toNode.nodeKey.file}, toNode.heading=${toNode.nodeKey.heading}`);
}
const edge = findEdgeBetween(
fromKey,
toKey,
@@ -560,21 +651,24 @@ function scoreAssignment(
canonicalEdgeType,
chainRoles,
edgeVocabulary,
edgeTargetResolutionMap || new Map()
edgeTargetResolutionMap || new Map(),
link.allowed_edge_roles
);
const effectiveRole = edge?.edgeRole ?? (edge ? inferRoleFromRawType(edge.rawEdgeType, chainRoles) : null);
getTemplateMatchingLogger().debugObject(`[scoreAssignment] Link ${link.from}→${link.to}`, {
fromKey,
toKey,
edgeFound: !!edge,
edgeType: edge?.rawEdgeType,
edgeRole: edge?.edgeRole,
effectiveRole,
allowedEdgeRoles: link.allowed_edge_roles,
matches: edge && effectiveRole && (!link.allowed_edge_roles || link.allowed_edge_roles.length === 0 || link.allowed_edge_roles.includes(effectiveRole))
});
// Enhanced debug logging for guides edge specifically
const isGuidesDebug = isGuidesDebugLink && fromKey.includes("learning");
if (isGuidesDebug || debugLogging) {
console.log(`[scoreAssignment] Link ${link.from}→${link.to}:`);
console.log(` edgeFound: ${!!edge}`);
console.log(` edgeType: ${edge?.rawEdgeType}`);
console.log(` edgeRole: ${edge?.edgeRole}`);
console.log(` effectiveRole: ${effectiveRole}`);
console.log(` inferRoleFromRawType(${edge?.rawEdgeType}): ${edge ? inferRoleFromRawType(edge.rawEdgeType, chainRoles) : "N/A"}`);
console.log(` allowedEdgeRoles: ${link.allowed_edge_roles?.join(", ") || "none"}`);
console.log(` matches: ${edge && effectiveRole && (!link.allowed_edge_roles || link.allowed_edge_roles.length === 0 || link.allowed_edge_roles.includes(effectiveRole))}`);
}
if (edge && effectiveRole) {
if (!link.allowed_edge_roles || link.allowed_edge_roles.length === 0) {
@@ -618,8 +712,6 @@ function scoreAssignment(
return { score, satisfiedLinks, requiredLinks, roleEvidence };
}
const MAX_ASSIGNMENTS_COLLECTED = 80;
/** Two assignments are distinct if at least one slot points to a different node. Uses normalized heading so "Feedback" and "Feedback ^block-id" count as the same section. */
function assignmentSignature(slots: ChainTemplateSlot[], assignment: Map<string, CandidateNode>): string {
const parts = slots.map((s) => {
@@ -632,6 +724,7 @@ function assignmentSignature(slots: ChainTemplateSlot[], assignment: Map<string,
/**
* Find top K distinct assignments for a template (e.g. intra-note and cross-note loop_learning).
* maxAssignmentsCollected: Schleifenschutz; nur konfigurierbar (YAML/Plugin), kein fester Wert.
*/
function findTopKAssignments(
template: ChainTemplate,
@@ -646,6 +739,7 @@ function findTopKAssignments(
templatesConfig?: ChainTemplatesConfig | null,
currentContextFile?: string,
topK: number = 2,
maxAssignmentsCollected: number = 1000,
debugLogging?: boolean
): TemplateMatch[] {
const slots = normalized.slots;
@@ -684,7 +778,7 @@ function findTopKAssignments(
currentContextFile,
debugLogging
);
if (collected.length < MAX_ASSIGNMENTS_COLLECTED) {
if (collected.length < maxAssignmentsCollected) {
collected.push({ assignment: new Map(assignment), score: result.score, result });
} else {
const minIdx = collected.reduce((i, c, j) => (c.score < (collected[i]?.score ?? c.score) ? j : i), 0);
@@ -735,7 +829,22 @@ function findTopKAssignments(
return missing === 0;
}).length;
getTemplateMatchingLogger().debug(`Template ${template.name}: collected=${collected.length}, complete=${completeCount}, will return up to ${topK}`);
if (debugLogging || template.name === "insight_to_decision") {
getTemplateMatchingLogger().debug(`Template ${template.name}: collected=${collected.length}, complete=${completeCount}, will return up to ${topK}`);
if (collected.length > 0) {
getTemplateMatchingLogger().debug(`First assignment: ${Array.from(collected[0]!.assignment.entries()).map(([slot, node]) => `${slot}=${node.nodeKey.file}#${node.nodeKey.heading}`).join(", ")}`);
getTemplateMatchingLogger().debug(`First score: ${collected[0]!.score}, satisfiedLinks: ${collected[0]!.result.satisfiedLinks}`);
} else {
getTemplateMatchingLogger().debug(`No assignments collected for template ${template.name}`);
// Debug: Prüfe Slot-Candidates
for (const slot of slots) {
const candidates = slotCandidates.get(slot.id) || [];
getTemplateMatchingLogger().debug(` Slot ${slot.id}: ${candidates.length} candidates`);
}
}
} else {
getTemplateMatchingLogger().debug(`Template ${template.name}: collected=${collected.length}, complete=${completeCount}, will return up to ${topK}`);
}
const shortFile = (path: string) => path.split("/").pop() || path;
const out: TemplateMatch[] = [];
@@ -834,7 +943,7 @@ function resolveEdgeTargetPath(
targetFile: string,
sourceFile: string
): string {
// If already a full path, return as is
// If already a full path (contains / or ends with .md), try direct lookup first
if (targetFile.includes("/") || targetFile.endsWith(".md")) {
const fileObj = app.vault.getAbstractFileByPath(targetFile);
if (fileObj && "path" in fileObj) {
@@ -842,12 +951,28 @@ function resolveEdgeTargetPath(
}
}
// Try to resolve as wikilink
// CRITICAL FIX: Check if targetFile matches sourceFile basename FIRST (before wikilink resolution)
// This handles intra-note links where targetFile is just the filename without path
const sourceBasename = sourceFile.split("/").pop()?.replace(/\.md$/, "") || "";
const targetBasename = targetFile.replace(/\.md$/, "");
// Also check if targetFile exactly matches sourceBasename (without .md extension)
if (sourceBasename === targetBasename || sourceBasename === targetFile) {
// Same file - return source file path
return sourceFile;
}
// Try to resolve as wikilink (handles both short names and paths)
// This is important for cross-note links
const resolved = app.metadataCache.getFirstLinkpathDest(targetFile, sourceFile);
if (resolved) {
return resolved.path;
}
// Additional check: if sourceFile ends with targetFile (e.g., "folder/file.md" ends with "file")
if (sourceFile.endsWith(targetFile) || sourceFile.endsWith(`${targetFile}.md`)) {
return sourceFile;
}
// Fallback: return original (will be handled as "unknown" type)
return targetFile;
}
@@ -862,7 +987,7 @@ export async function matchTemplates(
templatesConfig: ChainTemplatesConfig | null,
chainRoles: ChainRolesConfig | null,
edgeVocabulary: EdgeVocabulary | null,
options: { includeNoteLinks: boolean; includeCandidates: boolean; maxMatchesPerTemplateDefault?: number; debugLogging?: boolean },
options: { includeNoteLinks: boolean; includeCandidates: boolean; maxMatchesPerTemplateDefault?: number; maxAssignmentsCollectedDefault?: number; debugLogging?: boolean },
profile?: TemplateMatchingProfile
): Promise<TemplateMatch[]> {
if (!templatesConfig || !templatesConfig.templates || templatesConfig.templates.length === 0) {
@@ -879,12 +1004,43 @@ export async function matchTemplates(
Number.MAX_SAFE_INTEGER
);
// Create a map from original edge target to resolved path for edge matching
// Resolve both source and target file paths so findEdgeBetween matches even when
// edges use short names (e.g. "Note.md") and assignment keys use resolved paths.
const edgeTargetResolutionMap = new Map<string, string>();
const isGuidesDebug = options.debugLogging || false;
for (const edge of allEdges) {
const sourceFile = "sectionHeading" in edge.source ? edge.source.file : edge.source.file;
const resolved = resolveEdgeTargetPath(app, edge.target.file, sourceFile);
edgeTargetResolutionMap.set(edge.target.file, resolved);
const resolvedSource = resolveEdgeTargetPath(app, sourceFile, currentContext.file);
edgeTargetResolutionMap.set(sourceFile, resolvedSource);
// Resolve target file - use RESOLVED source file as context for intra-note links
// This is critical: use resolvedSource (not sourceFile) so intra-note links work correctly
let resolvedTarget = resolveEdgeTargetPath(app, edge.target.file, resolvedSource);
// CRITICAL FIX: Always check if target file matches source basename (intra-note link)
// This must happen AFTER resolveEdgeTargetPath, but we ensure it's set correctly
// Check both the original sourceFile basename and resolvedSource basename
const sourceBasename = resolvedSource.split("/").pop()?.replace(/\.md$/, "") || "";
const originalSourceBasename = sourceFile.split("/").pop()?.replace(/\.md$/, "") || "";
// If target file matches source basename, it's an intra-note link - use resolvedSource
if (sourceBasename === edge.target.file || originalSourceBasename === edge.target.file) {
resolvedTarget = resolvedSource;
}
// Also check if resolvedTarget is still the original targetFile (not resolved)
// This means resolveEdgeTargetPath didn't find it, so try again with explicit check
if (resolvedTarget === edge.target.file && !edge.target.file.includes("/") && !edge.target.file.endsWith(".md")) {
// Target file wasn't resolved - check if it matches source basename
if (sourceBasename === edge.target.file || originalSourceBasename === edge.target.file) {
resolvedTarget = resolvedSource;
}
}
// Always set the map entry
edgeTargetResolutionMap.set(edge.target.file, resolvedTarget);
}
// Create canonical edge type resolver
@@ -893,11 +1049,17 @@ export async function matchTemplates(
return result.canonical;
};
// Match each template; distinct assignments per template (e.g. intra-note + cross-note).
// Use the greater of YAML and plugin setting so plugin "2" is not overridden by YAML "1".
// max_matches_per_template: YAML > Plugin; 0 = no limit (nur durch max_assignments_collected begrenzt).
const yamlMax = templatesConfig.defaults?.matching?.max_matches_per_template ?? 0;
const pluginMax = options.maxMatchesPerTemplateDefault ?? 2;
const maxPerTemplate = Math.max(1, Math.min(10, Math.max(yamlMax, pluginMax)));
const maxPerTemplate = Math.max(yamlMax, pluginMax) === 0
? Number.MAX_SAFE_INTEGER
: Math.max(1, Math.max(yamlMax, pluginMax));
// Schleifenschutz: konfigurierbar (YAML > Plugin), kein willkürlicher fester Wert.
const maxAssignmentsCollected = templatesConfig.defaults?.matching?.max_assignments_collected
?? options.maxAssignmentsCollectedDefault
?? 1000;
const matches: TemplateMatch[] = [];
@@ -917,6 +1079,7 @@ export async function matchTemplates(
templatesConfig,
currentContext.file,
maxPerTemplate,
maxAssignmentsCollected,
options.debugLogging
);