Enhance UI and functionality for Chain Workbench and related features
- Introduced a wide two-column layout for the Chain Workbench modal, improving user experience and accessibility. - Added new styles for workbench components, including headers, filters, and main containers, to enhance visual organization. - Updated chain templates to allow for multiple distinct matches per template, improving flexibility in template matching. - Enhanced documentation to clarify the new settings and commands related to the Chain Workbench and edge detection features. - Implemented logging for better tracking of missing configurations, ensuring users are informed about any loading issues.
This commit is contained in:
1 parent
c044d6e8db
commit
725adb5302
47 files changed
+4161
-646
No files matched your search
@@ -9,11 +9,18 @@ import type { IndexedEdge, SectionNode } from "./graphIndex";
|
||||
import { buildNoteIndex, loadNeighborNote } from "./graphIndex";
|
||||
import type { ChainRolesConfig, ChainTemplatesConfig } from "../dictionary/types";
|
||||
import { splitIntoSections } from "../mapping/sectionParser";
|
||||
import { normalizeLinkTarget } from "../unresolvedLink/linkHelpers";
|
||||
import { normalizeLinkTarget, headingsMatch } from "../unresolvedLink/linkHelpers";
|
||||
import type { EdgeVocabulary } from "../vocab/types";
|
||||
import { parseEdgeVocabulary } from "../vocab/parseEdgeVocabulary";
|
||||
import { VocabularyLoader } from "../vocab/VocabularyLoader";
|
||||
import { applySeverityPolicy } from "./severityPolicy";
|
||||
import { getLogger, loggerRegistry } from "../utils/logger";
|
||||
|
||||
// Don't create logger instance at import time - create it when needed
|
||||
// This ensures it always reads current log levels from registry
|
||||
function getChainInspectorLogger() {
|
||||
return getLogger("chainInspector");
|
||||
}
|
||||
|
||||
export interface InspectorOptions {
|
||||
includeNoteLinks: boolean;
|
||||
@@ -21,6 +28,10 @@ export interface InspectorOptions {
|
||||
maxDepth: number;
|
||||
direction: "forward" | "backward" | "both";
|
||||
maxTemplateMatches?: number; // Optional: limit number of template matches (default: 3)
|
||||
/** Default max distinct matches per template. Overridable by chain_templates.yaml defaults.matching.max_matches_per_template. */
|
||||
maxMatchesPerTemplateDefault?: number; // default: 2
|
||||
/** When true, log template-matching details (candidates per slot, collected/complete counts, returned matches) to console. */
|
||||
debugLogging?: boolean;
|
||||
}
|
||||
|
||||
export interface Finding {
|
||||
@@ -196,7 +207,7 @@ function getNeighbors(
|
||||
// Match exact section (file + heading) OR note-level link (file only, heading null)
|
||||
const targetsCurrentSection =
|
||||
matchesCurrentFile(edge.target.file) &&
|
||||
(edge.target.heading === currentSection.heading ||
|
||||
(headingsMatch(edge.target.heading, currentSection.heading) ||
|
||||
(edge.target.heading === null && currentSection.heading !== null));
|
||||
|
||||
if (targetsCurrentSection) {
|
||||
@@ -221,7 +232,7 @@ function getNeighbors(
|
||||
// Check if edge originates from current section
|
||||
const sourceMatches =
|
||||
("sectionHeading" in edge.source
|
||||
? edge.source.sectionHeading === currentSection.heading &&
|
||||
? headingsMatch(edge.source.sectionHeading, currentSection.heading) &&
|
||||
edge.source.file === currentSection.file
|
||||
: edge.scope === "note" && edge.source.file === currentSection.file) &&
|
||||
edge.source.file === currentSection.file;
|
||||
@@ -307,7 +318,7 @@ function traverseForward(
|
||||
for (const edge of edges) {
|
||||
const sourceMatches =
|
||||
("sectionHeading" in edge.source
|
||||
? edge.source.sectionHeading === current.heading &&
|
||||
? headingsMatch(edge.source.sectionHeading, current.heading) &&
|
||||
edge.source.file === current.file
|
||||
: edge.scope === "note" && edge.source.file === current.file) &&
|
||||
edge.source.file === current.file;
|
||||
@@ -376,7 +387,7 @@ function traverseBackward(
|
||||
for (const edge of edges) {
|
||||
const targetsCurrentNode =
|
||||
matchesCurrentFile(edge.target.file) &&
|
||||
(edge.target.heading === current.heading ||
|
||||
(headingsMatch(edge.target.heading, current.heading) ||
|
||||
(edge.target.heading === null && current.heading !== null));
|
||||
|
||||
if (targetsCurrentNode) {
|
||||
@@ -434,9 +445,9 @@ function computeFindings(
|
||||
): Finding[] {
|
||||
const findings: Finding[] = [];
|
||||
|
||||
// Find current section content
|
||||
// Find current section content (normalized heading match for block-id variants)
|
||||
const currentSection = sections.find(
|
||||
(s) => s.file === context.file && s.heading === context.heading
|
||||
(s) => s.file === context.file && headingsMatch(s.heading, context.heading)
|
||||
);
|
||||
|
||||
if (!currentSection) {
|
||||
@@ -450,7 +461,7 @@ function computeFindings(
|
||||
|
||||
const sourceMatches =
|
||||
"sectionHeading" in edge.source
|
||||
? edge.source.sectionHeading === context.heading &&
|
||||
? headingsMatch(edge.source.sectionHeading, context.heading) &&
|
||||
edge.source.file === context.file
|
||||
: false;
|
||||
|
||||
@@ -498,7 +509,7 @@ function computeFindings(
|
||||
const incoming = filteredAllEdges.filter((edge) => {
|
||||
// Don't manually filter candidates here - filterEdges already did that based on options.includeCandidates
|
||||
const fileMatches = matchesCurrentFile(edge.target.file);
|
||||
const headingMatches = edge.target.heading === context.heading ||
|
||||
const headingMatches = headingsMatch(edge.target.heading, context.heading) ||
|
||||
(edge.target.heading === null && context.heading !== null);
|
||||
return fileMatches && headingMatches;
|
||||
});
|
||||
@@ -511,14 +522,14 @@ function computeFindings(
|
||||
const outgoing = filteredCurrentEdges.filter((edge) => {
|
||||
const sourceMatches =
|
||||
"sectionHeading" in edge.source
|
||||
? edge.source.sectionHeading === context.heading &&
|
||||
? headingsMatch(edge.source.sectionHeading, context.heading) &&
|
||||
edge.source.file === context.file
|
||||
: edge.scope === "note" && edge.source.file === context.file;
|
||||
return sourceMatches;
|
||||
});
|
||||
|
||||
// Debug logging for findings (use effective counts that match report.neighbors)
|
||||
console.log(`[Chain Inspector] computeFindings: incomingEffective=${incoming.length}, outgoingEffective=${outgoing.length}, allEdges=${allEdges.length}, filteredAllEdges=${filteredAllEdges.length}`);
|
||||
getChainInspectorLogger().debug(`computeFindings: incomingEffective=${incoming.length}, outgoingEffective=${outgoing.length}, allEdges=${allEdges.length}, filteredAllEdges=${filteredAllEdges.length}`);
|
||||
|
||||
if (incoming.length > 0 && outgoing.length === 0) {
|
||||
findings.push({
|
||||
@@ -547,7 +558,7 @@ function computeFindings(
|
||||
(edge) =>
|
||||
edge.scope === "candidate" &&
|
||||
("sectionHeading" in edge.source
|
||||
? edge.source.sectionHeading === context.heading &&
|
||||
? headingsMatch(edge.source.sectionHeading, context.heading) &&
|
||||
edge.source.file === context.file
|
||||
: false)
|
||||
);
|
||||
@@ -597,7 +608,7 @@ function computeFindings(
|
||||
// Use file cache to check headings
|
||||
const headings = targetContent.headings || [];
|
||||
const headingExists = headings.some(
|
||||
(h) => h.heading === targetHeading
|
||||
(h) => headingsMatch(h.heading, targetHeading)
|
||||
);
|
||||
|
||||
if (!headingExists) {
|
||||
@@ -704,7 +715,7 @@ export async function inspectChains(
|
||||
// Only consider edges from current context
|
||||
if (
|
||||
("sectionHeading" in edge.source
|
||||
? edge.source.sectionHeading === context.heading &&
|
||||
? headingsMatch(edge.source.sectionHeading, context.heading) &&
|
||||
edge.source.file === context.file
|
||||
: edge.scope === "note" && edge.source.file === context.file) &&
|
||||
edge.source.file === context.file
|
||||
@@ -727,14 +738,14 @@ export async function inspectChains(
|
||||
if (sourcePath === context.file) continue; // Skip self
|
||||
notesLinkingToCurrent.add(sourcePath);
|
||||
}
|
||||
console.log(`[Chain Inspector] Found ${notesLinkingToCurrent.size} notes linking to current note via getBacklinksForFile`);
|
||||
getChainInspectorLogger().debug(`Found ${notesLinkingToCurrent.size} notes linking to current note via getBacklinksForFile`);
|
||||
} else {
|
||||
console.log("[Chain Inspector] getBacklinksForFile returned null/undefined");
|
||||
getChainInspectorLogger().debug("getBacklinksForFile returned null/undefined");
|
||||
}
|
||||
} catch (e) {
|
||||
// Fallback: if getBacklinksForFile is not available, use manual scan
|
||||
// This should rarely happen, but provides compatibility
|
||||
console.warn("getBacklinksForFile not available, falling back to manual scan", e);
|
||||
getChainInspectorLogger().warn("getBacklinksForFile not available, falling back to manual scan", e);
|
||||
|
||||
const currentNoteBasename = (currentFile as TFile).basename;
|
||||
const currentNotePath = context.file;
|
||||
@@ -789,7 +800,7 @@ export async function inspectChains(
|
||||
const outgoingNeighborFileMap = new Map<string, TFile>(); // original target -> resolved TFile
|
||||
|
||||
// Resolve outgoing targets (may be basenames without folder)
|
||||
console.log(`[Chain Inspector] Loading outgoing neighbor notes: ${outgoingTargets.size}`);
|
||||
getChainInspectorLogger().debug(`Loading outgoing neighbor notes: ${outgoingTargets.size}`);
|
||||
for (const targetFile of outgoingTargets) {
|
||||
if (targetFile === context.file) continue; // Skip self
|
||||
|
||||
@@ -807,7 +818,7 @@ export async function inspectChains(
|
||||
if (neighborFile && "extension" in neighborFile && neighborFile.extension === "md") {
|
||||
const { edges: neighborEdges } = await buildNoteIndex(app, neighborFile as TFile);
|
||||
allEdges.push(...neighborEdges);
|
||||
console.log(`[Chain Inspector] Loaded ${neighborEdges.length} edges from ${neighborPath} (outgoing neighbor)`);
|
||||
getChainInspectorLogger().debug(`Loaded ${neighborEdges.length} edges from ${neighborPath} (outgoing neighbor)`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -815,7 +826,9 @@ export async function inspectChains(
|
||||
// Deduplicate with outgoing neighbors (same file might be both incoming and outgoing)
|
||||
const allNeighborFiles = new Set<string>([...outgoingNeighborFiles]);
|
||||
|
||||
console.log(`[Chain Inspector] Loading ${notesLinkingToCurrent.size} notes that link to current note`);
|
||||
if (options.debugLogging) {
|
||||
getChainInspectorLogger().debug(`Loading ${notesLinkingToCurrent.size} notes that link to current note`);
|
||||
}
|
||||
for (const sourceFile of notesLinkingToCurrent) {
|
||||
if (sourceFile === context.file) continue; // Skip self
|
||||
if (allNeighborFiles.has(sourceFile)) continue; // Skip if already loaded as outgoing neighbor
|
||||
@@ -824,16 +837,16 @@ export async function inspectChains(
|
||||
if (sourceNoteFile) {
|
||||
allNeighborFiles.add(sourceNoteFile.path);
|
||||
const { edges: sourceEdges } = await buildNoteIndex(app, sourceNoteFile);
|
||||
console.log(`[Chain Inspector] Loaded ${sourceEdges.length} edges from ${sourceFile}`);
|
||||
getChainInspectorLogger().debug(`Loaded ${sourceEdges.length} edges from ${sourceFile}`);
|
||||
|
||||
// Debug: Show all edges from this file (first 5) to understand what we're working with
|
||||
if (sourceEdges.length > 0) {
|
||||
console.log(`[Chain Inspector] Sample edges from ${sourceFile} (showing first 5):`);
|
||||
getChainInspectorLogger().debug(`Sample edges from ${sourceFile} (showing first 5):`);
|
||||
for (const edge of sourceEdges.slice(0, 5)) {
|
||||
const sourceInfo = "sectionHeading" in edge.source
|
||||
? `${edge.source.file}#${edge.source.sectionHeading || "null"}`
|
||||
: `${edge.source.file} (note-level)`;
|
||||
console.log(` - ${edge.rawEdgeType} from ${sourceInfo} -> ${edge.target.file}#${edge.target.heading || "null"}`);
|
||||
getChainInspectorLogger().debug(` - ${edge.rawEdgeType} from ${sourceInfo} -> ${edge.target.file}#${edge.target.heading || "null"}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -850,16 +863,16 @@ export async function inspectChains(
|
||||
return false;
|
||||
});
|
||||
if (edgesTargetingCurrentNote.length > 0) {
|
||||
console.log(`[Chain Inspector] ✓ Found ${edgesTargetingCurrentNote.length} edges from ${sourceFile} targeting current note (${context.file}):`);
|
||||
getChainInspectorLogger().debug(`✓ Found ${edgesTargetingCurrentNote.length} edges from ${sourceFile} targeting current note (${context.file}):`);
|
||||
for (const edge of edgesTargetingCurrentNote) {
|
||||
const sourceInfo = "sectionHeading" in edge.source
|
||||
? `${edge.source.file}#${edge.source.sectionHeading || "null"}`
|
||||
: `${edge.source.file} (note-level)`;
|
||||
console.log(` - ${edge.rawEdgeType} from ${sourceInfo} -> ${edge.target.file}#${edge.target.heading || "null"} [scope: ${edge.scope}]`);
|
||||
getChainInspectorLogger().debug(` - ${edge.rawEdgeType} from ${sourceInfo} -> ${edge.target.file}#${edge.target.heading || "null"} [scope: ${edge.scope}]`);
|
||||
}
|
||||
// Check why they don't match current section
|
||||
const currentSectionKey = `${context.file}:${context.heading || "null"}`;
|
||||
console.log(`[Chain Inspector] Current section: ${currentSectionKey}`);
|
||||
getChainInspectorLogger().debug(`Current section: ${currentSectionKey}`);
|
||||
// Use same matching logic as getNeighbors
|
||||
const debugFileBasename = context.file.split("/").pop()?.replace(/\.md$/, "") || "";
|
||||
const matchesCurrentFileDebug = (targetFile: string): boolean => {
|
||||
@@ -874,18 +887,18 @@ export async function inspectChains(
|
||||
for (const edge of edgesTargetingCurrentNote) {
|
||||
const targetKey = `${edge.target.file}:${edge.target.heading || "null"}`;
|
||||
const fileMatches = matchesCurrentFileDebug(edge.target.file);
|
||||
const headingMatches = edge.target.heading === context.heading ||
|
||||
const headingMatches = headingsMatch(edge.target.heading, context.heading) ||
|
||||
(edge.target.heading === null && context.heading !== null);
|
||||
const matches = fileMatches && headingMatches;
|
||||
console.log(` - Edge target: ${targetKey}, file matches: ${fileMatches ? "YES" : "NO"}, heading matches: ${headingMatches ? "YES" : "NO"}, should match: ${matches ? "YES" : "NO"}`);
|
||||
getChainInspectorLogger().debug(` - Edge target: ${targetKey}, file matches: ${fileMatches ? "YES" : "NO"}, heading matches: ${headingMatches ? "YES" : "NO"}, should match: ${matches ? "YES" : "NO"}`);
|
||||
}
|
||||
} else {
|
||||
console.log(`[Chain Inspector] ✗ No edges from ${sourceFile} target current note (${context.file})`);
|
||||
console.log(` - Edges in this file target: ${[...new Set(sourceEdges.map(e => e.target.file))].slice(0, 3).join(", ")}...`);
|
||||
getChainInspectorLogger().debug(`✗ No edges from ${sourceFile} target current note (${context.file})`);
|
||||
getChainInspectorLogger().debug(` - Edges in this file target: ${[...new Set(sourceEdges.map(e => e.target.file))].slice(0, 3).join(", ")}...`);
|
||||
}
|
||||
allEdges.push(...sourceEdges);
|
||||
} else {
|
||||
console.log(`[Chain Inspector] Could not load neighbor note: ${sourceFile}`);
|
||||
getChainInspectorLogger().debug(`Could not load neighbor note: ${sourceFile}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -896,9 +909,9 @@ export async function inspectChains(
|
||||
sectionsWithContent[context.sectionIndex]?.content || "";
|
||||
|
||||
// Get neighbors (now includes edges from neighbor notes)
|
||||
console.log(`[Chain Inspector] Total edges after loading neighbors: ${allEdges.length} (current: ${currentEdges.length}, neighbors: ${allEdges.length - currentEdges.length})`);
|
||||
getChainInspectorLogger().debug(`Total edges after loading neighbors: ${allEdges.length} (current: ${currentEdges.length}, neighbors: ${allEdges.length - currentEdges.length})`);
|
||||
const neighbors = getNeighbors(allEdges, context, options);
|
||||
console.log(`[Chain Inspector] Neighbors found: ${neighbors.incoming.length} incoming, ${neighbors.outgoing.length} outgoing`);
|
||||
getChainInspectorLogger().debug(`Neighbors found: ${neighbors.incoming.length} incoming, ${neighbors.outgoing.length} outgoing`);
|
||||
|
||||
// Traverse paths (now includes edges from neighbor notes)
|
||||
const paths = traversePaths(allEdges, context, options);
|
||||
@@ -910,7 +923,7 @@ export async function inspectChains(
|
||||
const vocabText = await VocabularyLoader.loadText(app, edgeVocabularyPath);
|
||||
edgeVocabulary = parseEdgeVocabulary(vocabText);
|
||||
} catch (error) {
|
||||
console.warn(`[Chain Inspector] Could not load edge vocabulary from ${edgeVocabularyPath}:`, error);
|
||||
getChainInspectorLogger().warn(`Could not load edge vocabulary from ${edgeVocabularyPath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -920,7 +933,7 @@ export async function inspectChains(
|
||||
const effectiveIncomingCount = neighbors.incoming.length;
|
||||
const effectiveOutgoingCount = neighbors.outgoing.length;
|
||||
const effectiveFilteredEdges = filterEdges(allEdges, options);
|
||||
console.log(`[Chain Inspector] Before computeFindings: effectiveIncoming=${effectiveIncomingCount}, effectiveOutgoing=${effectiveOutgoingCount}, effectiveFilteredEdges=${effectiveFilteredEdges.length}`);
|
||||
getChainInspectorLogger().debug(`Before computeFindings: effectiveIncoming=${effectiveIncomingCount}, effectiveOutgoing=${effectiveOutgoingCount}, effectiveFilteredEdges=${effectiveFilteredEdges.length}`);
|
||||
|
||||
let findings = computeFindings(
|
||||
allEdges, // Use allEdges so we can detect incoming edges from neighbor notes
|
||||
@@ -992,8 +1005,9 @@ export async function inspectChains(
|
||||
|
||||
// Log start-of-run header with resolved profile and settings
|
||||
const requiredLinks = profile?.required_links ?? false;
|
||||
console.log(
|
||||
`[Chain Inspector] Run: profile=${profileName} (resolvedFrom=${resolvedFrom}) required_links=${requiredLinks} includeCandidates=${options.includeCandidates} maxDepth=${options.maxDepth} direction=${options.direction}`
|
||||
|
||||
getChainInspectorLogger().info(
|
||||
`Run: profile=${profileName} (resolvedFrom=${resolvedFrom}) required_links=${requiredLinks} includeCandidates=${options.includeCandidates} maxDepth=${options.maxDepth} direction=${options.direction}`
|
||||
);
|
||||
|
||||
// Template matching
|
||||
@@ -1052,9 +1066,24 @@ export async function inspectChains(
|
||||
return a.templateName.localeCompare(b.templateName);
|
||||
});
|
||||
|
||||
// Limit to topN (default: 3, configurable via options.maxTemplateMatches)
|
||||
// Limit to topN per template (default: 3), so up to N chains per chain type, not N total
|
||||
const topN = options.maxTemplateMatches ?? 3;
|
||||
templateMatches = sortedMatches.slice(0, topN);
|
||||
const byTemplate = new Map<string, typeof allTemplateMatches>();
|
||||
for (const m of sortedMatches) {
|
||||
const list = byTemplate.get(m.templateName) ?? [];
|
||||
list.push(m);
|
||||
byTemplate.set(m.templateName, list);
|
||||
}
|
||||
templateMatches = [];
|
||||
for (const list of byTemplate.values()) {
|
||||
templateMatches.push(...list.slice(0, topN));
|
||||
}
|
||||
templateMatches.sort((a, b) => {
|
||||
const rankDiff = confidenceRank(b.confidence) - confidenceRank(a.confidence);
|
||||
if (rankDiff !== 0) return rankDiff;
|
||||
if (b.score !== a.score) return b.score - a.score;
|
||||
return a.templateName.localeCompare(b.templateName);
|
||||
});
|
||||
|
||||
// Store topNUsed in analysisMeta
|
||||
if (analysisMeta) {
|
||||
@@ -1128,7 +1157,7 @@ export async function inspectChains(
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[Chain Inspector] Template matching failed:", e);
|
||||
getChainInspectorLogger().error("Template matching failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,15 +34,40 @@ export interface SectionNode {
|
||||
const NOTE_LINKS_HEADING = "Note-Verbindungen";
|
||||
const CANDIDATES_HEADING = "Kandidaten";
|
||||
|
||||
/** Intra-note block reference: [[#^block-id]] or [[#^block-id|alias]] */
|
||||
const INTRA_NOTE_BLOCK_REF_RE = /^#\^([a-zA-Z0-9_-]+)(?:\s*\|.*)?$/;
|
||||
|
||||
/**
|
||||
* Parse target from link text: [[file]] or [[file#Heading]]
|
||||
* Resolve [[#^block-id]] to (currentFile, sectionHeading) using section blockIds.
|
||||
* Returns null if not an intra-note block ref.
|
||||
*/
|
||||
function parseTarget(linkText: string): EdgeTarget {
|
||||
function resolveIntraNoteBlockRef(
|
||||
linkText: string,
|
||||
currentFilePath: string,
|
||||
sections: NoteSection[]
|
||||
): EdgeTarget | null {
|
||||
const trimmed = linkText.trim();
|
||||
const match = trimmed.match(INTRA_NOTE_BLOCK_REF_RE);
|
||||
if (!match) return null;
|
||||
const blockId = match[1];
|
||||
const section = sections.find((s) => s.blockId === blockId);
|
||||
return {
|
||||
file: currentFilePath,
|
||||
heading: section?.heading ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse target from link text: [[file]], [[file#Heading]], or [[#^block-id]] (intra-note).
|
||||
*/
|
||||
function parseTarget(linkText: string, currentFilePath: string, sections: NoteSection[]): EdgeTarget {
|
||||
const intraNote = resolveIntraNoteBlockRef(linkText, currentFilePath, sections);
|
||||
if (intraNote) return intraNote;
|
||||
|
||||
const normalized = normalizeLinkTarget(linkText);
|
||||
const parts = linkText.split("#");
|
||||
|
||||
|
||||
if (parts.length > 1) {
|
||||
// Has heading: [[file#Heading]]
|
||||
const file = normalized;
|
||||
const headingPart = parts[1]?.split("|")[0]?.trim();
|
||||
return {
|
||||
@@ -50,8 +75,7 @@ function parseTarget(linkText: string): EdgeTarget {
|
||||
heading: headingPart || null,
|
||||
};
|
||||
}
|
||||
|
||||
// No heading: [[file]]
|
||||
|
||||
return {
|
||||
file: normalized,
|
||||
heading: null,
|
||||
@@ -100,9 +124,9 @@ export async function buildNoteIndex(
|
||||
? { file: file.path }
|
||||
: { file: file.path, sectionHeading: section.heading };
|
||||
|
||||
// Process each target
|
||||
// Process each target (resolve [[#^block-id]] to same-note section)
|
||||
for (const targetLink of parsedEdge.targets) {
|
||||
const target = parseTarget(targetLink);
|
||||
const target = parseTarget(targetLink, file.path, sections);
|
||||
|
||||
edges.push({
|
||||
rawEdgeType: parsedEdge.rawType,
|
||||
|
||||
+434
-132
@@ -8,6 +8,14 @@ import type { ChainRolesConfig } from "../dictionary/types";
|
||||
import type { IndexedEdge } from "./graphIndex";
|
||||
import type { EdgeVocabulary } from "../vocab/types";
|
||||
import { resolveCanonicalEdgeType } from "./chainInspector";
|
||||
import { splitIntoSections } from "../mapping/sectionParser";
|
||||
import { headingsMatch, normalizeHeadingForMatch } from "../unresolvedLink/linkHelpers";
|
||||
import { getLogger } from "../utils/logger";
|
||||
|
||||
// Don't create logger instance at import time - create it when needed
|
||||
function getTemplateMatchingLogger() {
|
||||
return getLogger("templateMatching");
|
||||
}
|
||||
|
||||
export interface NodeKey {
|
||||
file: string;
|
||||
@@ -16,7 +24,10 @@ export interface NodeKey {
|
||||
|
||||
export interface CandidateNode {
|
||||
nodeKey: NodeKey;
|
||||
noteType: string; // "unknown" if not found
|
||||
/** Note-level type from frontmatter `type:`. */
|
||||
noteType: string;
|
||||
/** WP-26: Section-type or note-type used for slot matching: sectionType ?? noteType. */
|
||||
effectiveType: string;
|
||||
}
|
||||
|
||||
export interface TemplateMatch {
|
||||
@@ -161,13 +172,16 @@ async function buildCandidateNodes(
|
||||
currentContext: { file: string; heading: string | null },
|
||||
allEdges: IndexedEdge[],
|
||||
options: { includeNoteLinks: boolean; includeCandidates: boolean },
|
||||
maxNodes: number = 30
|
||||
maxNodes: number = Number.MAX_SAFE_INTEGER // Remove limit: process all nodes to find all edges
|
||||
): Promise<CandidateNode[]> {
|
||||
const nodeKeys = new Set<string>();
|
||||
const nodeMap = new Map<string, CandidateNode>();
|
||||
|
||||
// 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) ?? "";
|
||||
|
||||
// Add current context node
|
||||
const currentKey = `${currentContext.file}:${currentContext.heading || ""}`;
|
||||
const currentKey = `${currentContext.file}:${norm(currentContext.heading)}`;
|
||||
nodeKeys.add(currentKey);
|
||||
|
||||
// Add all target nodes from edges
|
||||
@@ -175,13 +189,13 @@ async function buildCandidateNodes(
|
||||
if (edge.scope === "candidate" && !options.includeCandidates) continue;
|
||||
if (edge.scope === "note" && !options.includeNoteLinks) continue;
|
||||
|
||||
const targetKey = `${edge.target.file}:${edge.target.heading || ""}`;
|
||||
const targetKey = `${edge.target.file}:${norm(edge.target.heading)}`;
|
||||
nodeKeys.add(targetKey);
|
||||
|
||||
// Add source nodes (for incoming edges)
|
||||
// Note: Source files should already be full paths from graphIndex
|
||||
if ("sectionHeading" in edge.source) {
|
||||
const sourceKey = `${edge.source.file}:${edge.source.sectionHeading || ""}`;
|
||||
const sourceKey = `${edge.source.file}:${norm(edge.source.sectionHeading)}`;
|
||||
nodeKeys.add(sourceKey);
|
||||
} else {
|
||||
const sourceKey = `${edge.source.file}:`;
|
||||
@@ -189,28 +203,37 @@ async function buildCandidateNodes(
|
||||
}
|
||||
}
|
||||
|
||||
// Limit to maxNodes (deterministic sorting)
|
||||
const sortedKeys = Array.from(nodeKeys).sort();
|
||||
const limitedKeys = sortedKeys.slice(0, maxNodes);
|
||||
// Prioritize nodes from current note (intra-note chains have highest probability)
|
||||
const currentFile = currentContext.file;
|
||||
const currentNoteKeys = Array.from(nodeKeys).filter((k) => {
|
||||
const i = k.indexOf(":");
|
||||
const file = i >= 0 ? k.slice(0, i) : k;
|
||||
return file === currentFile;
|
||||
}).sort();
|
||||
const otherKeys = Array.from(nodeKeys).filter((k) => {
|
||||
const i = k.indexOf(":");
|
||||
const file = i >= 0 ? k.slice(0, i) : k;
|
||||
return file !== currentFile;
|
||||
}).sort();
|
||||
const limitedKeys = [...currentNoteKeys, ...otherKeys].slice(0, maxNodes);
|
||||
|
||||
// Load note types for each node
|
||||
// Load note types and sections (for effective_type) per file
|
||||
const candidateNodes: CandidateNode[] = [];
|
||||
const fileCache = new Map<string, string>(); // resolved file path -> noteType
|
||||
const fileCache = new Map<string, string>(); // resolved path -> noteType
|
||||
const sectionsCache = new Map<string, ReturnType<typeof splitIntoSections>>(); // resolved path -> sections
|
||||
const pathResolutionCache = new Map<string, string | null>(); // original file -> resolved path
|
||||
|
||||
for (const key of limitedKeys) {
|
||||
const [file, heading] = key.split(":");
|
||||
const colonIndex = key.indexOf(":");
|
||||
const file = colonIndex >= 0 ? key.slice(0, colonIndex) : key;
|
||||
const heading = colonIndex >= 0 ? key.slice(colonIndex + 1) : "";
|
||||
if (!file) continue;
|
||||
|
||||
// Resolve file path (handle both full paths and link names)
|
||||
let resolvedPath = pathResolutionCache.get(file);
|
||||
if (resolvedPath === undefined) {
|
||||
// Try direct path first
|
||||
let fileObj = app.vault.getAbstractFileByPath(file);
|
||||
|
||||
// If not found and doesn't look like a full path, try resolving as link
|
||||
if (!fileObj && !file.includes("/") && !file.endsWith(".md")) {
|
||||
// Try to resolve as wikilink from current context
|
||||
const resolved = app.metadataCache.getFirstLinkpathDest(file, currentContext.file);
|
||||
if (resolved) {
|
||||
fileObj = resolved;
|
||||
@@ -223,35 +246,85 @@ async function buildCandidateNodes(
|
||||
} else {
|
||||
resolvedPath = null;
|
||||
}
|
||||
|
||||
pathResolutionCache.set(file, resolvedPath);
|
||||
}
|
||||
|
||||
if (!resolvedPath) {
|
||||
// File not found, skip this node
|
||||
continue;
|
||||
}
|
||||
if (!resolvedPath) continue;
|
||||
|
||||
// Get note type (cache per resolved file path)
|
||||
// Load note type and sections (WP-26: sectionType for effective_type)
|
||||
let noteType = fileCache.get(resolvedPath);
|
||||
if (noteType === undefined) {
|
||||
let sections = sectionsCache.get(resolvedPath);
|
||||
if (noteType === undefined || sections === undefined) {
|
||||
try {
|
||||
const fileObj = app.vault.getAbstractFileByPath(resolvedPath);
|
||||
if (fileObj && "extension" in fileObj && fileObj.extension === "md") {
|
||||
const content = await app.vault.cachedRead(fileObj as TFile);
|
||||
noteType = extractNoteType(content);
|
||||
if (noteType === undefined) {
|
||||
noteType = extractNoteType(content);
|
||||
fileCache.set(resolvedPath, noteType);
|
||||
}
|
||||
if (sections === undefined) {
|
||||
sections = splitIntoSections(content);
|
||||
sectionsCache.set(resolvedPath, sections);
|
||||
}
|
||||
} else {
|
||||
noteType = "unknown";
|
||||
if (noteType === undefined) {
|
||||
noteType = "unknown";
|
||||
fileCache.set(resolvedPath, noteType);
|
||||
}
|
||||
if (sections === undefined) {
|
||||
sections = [];
|
||||
sectionsCache.set(resolvedPath, sections);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
noteType = "unknown";
|
||||
if (noteType === undefined) {
|
||||
noteType = "unknown";
|
||||
fileCache.set(resolvedPath, noteType);
|
||||
}
|
||||
if (sections === undefined) {
|
||||
sections = [];
|
||||
sectionsCache.set(resolvedPath, sections);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// effective_type: sectionType ?? noteType (WP-26); use section's actual heading for display when matched
|
||||
const headingOrNull = heading || null;
|
||||
|
||||
// Rule: If this is a note-level node (heading === null), check if the note has multiple sections
|
||||
// with different types. If so, skip the note-level node - only individual sections should be candidates.
|
||||
if (!headingOrNull && sections.length > 0) {
|
||||
// Check if there are multiple sections with different effective types
|
||||
const sectionTypes = new Set<string>();
|
||||
for (const section of sections) {
|
||||
const sectionEffectiveType = section.sectionType || noteType;
|
||||
sectionTypes.add(sectionEffectiveType);
|
||||
}
|
||||
|
||||
// If there are multiple different types, skip note-level node
|
||||
if (sectionTypes.size > 1) {
|
||||
getTemplateMatchingLogger().debug(
|
||||
`Skipping note-level node for ${resolvedPath}: note has ${sectionTypes.size} different section types (${Array.from(sectionTypes).join(", ")})`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let effectiveType = noteType;
|
||||
let displayHeading: string | null = headingOrNull;
|
||||
if (headingOrNull && sections.length > 0) {
|
||||
const section = sections.find((s) => headingsMatch(s.heading, headingOrNull));
|
||||
if (section) {
|
||||
if (section.sectionType) effectiveType = section.sectionType;
|
||||
displayHeading = section.heading; // canonical heading from file (e.g. with ^block-id)
|
||||
}
|
||||
fileCache.set(resolvedPath, noteType);
|
||||
}
|
||||
|
||||
candidateNodes.push({
|
||||
nodeKey: { file: resolvedPath, heading: heading || null },
|
||||
nodeKey: { file: resolvedPath, heading: displayHeading },
|
||||
noteType,
|
||||
effectiveType,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -282,24 +355,34 @@ function getEdgeRole(
|
||||
|
||||
/**
|
||||
* Check if node matches slot constraints.
|
||||
* Strict: if allowed_node_types is defined, node must match exactly.
|
||||
* Uses effectiveType (sectionType ?? noteType) for WP-26 section-type-aware matching.
|
||||
*/
|
||||
function nodeMatchesSlot(
|
||||
node: CandidateNode,
|
||||
slot: ChainTemplateSlot
|
||||
): boolean {
|
||||
// If slot has allowed_node_types defined, enforce strict matching
|
||||
if (slot.allowed_node_types && slot.allowed_node_types.length > 0) {
|
||||
return slot.allowed_node_types.includes(node.noteType);
|
||||
return slot.allowed_node_types.includes(node.effectiveType);
|
||||
}
|
||||
|
||||
// No constraints = any type allowed (permissive behavior for backward compatibility)
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Parse node key "file:heading" (file may contain path with /). */
|
||||
function parseNodeKey(key: string): { file: string; heading: string | null } {
|
||||
const i = key.lastIndexOf(":");
|
||||
if (i < 0) return { file: key, heading: null };
|
||||
return { file: key.slice(0, i), heading: key.slice(i + 1) || null };
|
||||
}
|
||||
|
||||
/** Normalize path for comparison (vault paths: forward slashes, no trailing slash). */
|
||||
function normalizePathForComparison(path: string): string {
|
||||
return path.trim().replace(/\\/g, "/").replace(/\/+$/, "") || path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find edge between two nodes.
|
||||
* Uses resolved paths from candidate nodes and edge target resolution map.
|
||||
* Uses resolved paths and headingsMatch for heading comparison (block-id variants).
|
||||
* Paths are normalized so different slash styles (e.g. Windows) still match.
|
||||
*/
|
||||
function findEdgeBetween(
|
||||
fromKey: string,
|
||||
@@ -310,37 +393,111 @@ function findEdgeBetween(
|
||||
edgeVocabulary: EdgeVocabulary | null,
|
||||
edgeTargetResolutionMap: Map<string, string>
|
||||
): { edgeRole: string | null; rawEdgeType: string } | null {
|
||||
const [fromFile, fromHeading] = fromKey.split(":");
|
||||
const [toFile, toHeading] = toKey.split(":");
|
||||
|
||||
const { file: fromFile, heading: fromHeading } = parseNodeKey(fromKey);
|
||||
const { file: toFile, heading: toHeading } = parseNodeKey(toKey);
|
||||
const fromFileNorm = normalizePathForComparison(fromFile);
|
||||
const toFileNorm = normalizePathForComparison(toFile);
|
||||
|
||||
for (const edge of allEdges) {
|
||||
// Resolve source file path
|
||||
const sourceFile = "sectionHeading" in edge.source ? edge.source.file : edge.source.file;
|
||||
const resolvedSourceFile = sourceFile.includes("/") || sourceFile.endsWith(".md")
|
||||
? sourceFile
|
||||
: edgeTargetResolutionMap.get(sourceFile) || sourceFile;
|
||||
|
||||
// Resolve target file path
|
||||
const resolvedTargetFile = edgeTargetResolutionMap.get(edge.target.file) || edge.target.file;
|
||||
|
||||
const edgeFromKey = "sectionHeading" in edge.source
|
||||
? `${resolvedSourceFile}:${edge.source.sectionHeading || ""}`
|
||||
: `${resolvedSourceFile}:`;
|
||||
const edgeToKey = `${resolvedTargetFile}:${edge.target.heading || ""}`;
|
||||
|
||||
// Match keys (handle null heading as empty string)
|
||||
if (edgeFromKey === fromKey && edgeToKey === toKey) {
|
||||
const resolvedSourceNorm = normalizePathForComparison(resolvedSourceFile);
|
||||
const resolvedTargetNorm = normalizePathForComparison(resolvedTargetFile);
|
||||
|
||||
const sourceHeading = "sectionHeading" in edge.source ? edge.source.sectionHeading : null;
|
||||
const targetHeading = edge.target.heading;
|
||||
|
||||
if (
|
||||
resolvedSourceNorm === fromFileNorm &&
|
||||
headingsMatch(sourceHeading, fromHeading) &&
|
||||
resolvedTargetNorm === toFileNorm &&
|
||||
headingsMatch(targetHeading, toHeading)
|
||||
) {
|
||||
const canonical = canonicalEdgeType(edge.rawEdgeType);
|
||||
const edgeRole = getEdgeRole(edge.rawEdgeType, canonical, chainRoles);
|
||||
return { edgeRole, rawEdgeType: edge.rawEdgeType };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Diagnostic: when a link is not satisfied, log why (for learning→behavior / section_edges debugging).
|
||||
*/
|
||||
function logLinkResolutionDiagnostic(
|
||||
link: { from: string; to: string },
|
||||
fromKey: string,
|
||||
toKey: string,
|
||||
allEdges: IndexedEdge[],
|
||||
edgeTargetResolutionMap: Map<string, string>,
|
||||
chainRoles: ChainRolesConfig | null
|
||||
): void {
|
||||
// Only log for specific links we're debugging to avoid flooding console
|
||||
// Focus on learning->behavior or other critical links
|
||||
const isDebugLink = (link.from === "learning" && link.to === "behavior") ||
|
||||
(link.from === "experience" && link.to === "insight") ||
|
||||
(link.from === "insight" && link.to === "decision");
|
||||
|
||||
if (!isDebugLink) {
|
||||
return; // Skip logging for other links to reduce noise
|
||||
}
|
||||
|
||||
const { file: fromFile } = parseNodeKey(fromKey);
|
||||
const { file: toFile, heading: toHeading } = parseNodeKey(toKey);
|
||||
const fromFileNorm = normalizePathForComparison(fromFile);
|
||||
const toFileNorm = normalizePathForComparison(toFile);
|
||||
|
||||
const candidates = allEdges.filter((e) => {
|
||||
const sf = "sectionHeading" in e.source ? e.source.file : e.source.file;
|
||||
const resolved = sf.includes("/") || sf.endsWith(".md") ? sf : edgeTargetResolutionMap.get(sf) || sf;
|
||||
return normalizePathForComparison(resolved) === fromFileNorm;
|
||||
});
|
||||
|
||||
getTemplateMatchingLogger().debug(`link_resolution: ${link.from}→${link.to} fromKey=${fromKey} toKey=${toKey} candidates_from_same_file=${candidates.length}`);
|
||||
// Limit to first 5 candidates instead of 10 to reduce log size
|
||||
for (const e of candidates.slice(0, 5)) {
|
||||
const srcH = "sectionHeading" in e.source ? e.source.sectionHeading : null;
|
||||
const resT = edgeTargetResolutionMap.get(e.target.file) || e.target.file;
|
||||
const resTNorm = normalizePathForComparison(resT);
|
||||
const fileMatch = resTNorm === toFileNorm;
|
||||
const srcMatch = headingsMatch(srcH, parseNodeKey(fromKey).heading);
|
||||
const tgtMatch = headingsMatch(e.target.heading, toHeading);
|
||||
getTemplateMatchingLogger().debug(` - ${e.rawEdgeType} sourceHeading=${JSON.stringify(srcH)} targetFile=${e.target.file} targetHeading=${JSON.stringify(e.target.heading)} | srcMatch=${srcMatch} tgtFileMatch=${fileMatch} tgtHeadingMatch=${tgtMatch}`);
|
||||
}
|
||||
const withMatchingTarget = candidates.filter((e) => {
|
||||
const resT = edgeTargetResolutionMap.get(e.target.file) || e.target.file;
|
||||
return (
|
||||
normalizePathForComparison(resT) === toFileNorm &&
|
||||
headingsMatch(e.target.heading, toHeading) &&
|
||||
headingsMatch("sectionHeading" in e.source ? e.source.sectionHeading : null, parseNodeKey(fromKey).heading)
|
||||
);
|
||||
});
|
||||
if (withMatchingTarget.length > 0 && chainRoles) {
|
||||
for (const e of withMatchingTarget) {
|
||||
const role = getEdgeRole(e.rawEdgeType, undefined, chainRoles);
|
||||
getTemplateMatchingLogger().debug(` -> edge ${e.rawEdgeType} would match link but getEdgeRole=${role ?? "null"} (check chain_roles for this type)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer role from rawEdgeType by looking up in chainRoles (fallback when getEdgeRole returns null).
|
||||
*/
|
||||
function inferRoleFromRawType(rawEdgeType: string, chainRoles: ChainRolesConfig | null): string | null {
|
||||
if (!chainRoles) return null;
|
||||
for (const [roleName, role] of Object.entries(chainRoles.roles)) {
|
||||
if (role.edge_types?.includes(rawEdgeType)) return roleName;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Score assignment for template matching.
|
||||
* Boosts assignments where all nodes are in the same note (intra-note chains have highest probability).
|
||||
*/
|
||||
function scoreAssignment(
|
||||
template: ChainTemplate,
|
||||
@@ -351,7 +508,9 @@ function scoreAssignment(
|
||||
chainRoles: ChainRolesConfig | null,
|
||||
edgeVocabulary: EdgeVocabulary | null,
|
||||
profile?: TemplateMatchingProfile,
|
||||
edgeTargetResolutionMap?: Map<string, string>
|
||||
edgeTargetResolutionMap?: Map<string, string>,
|
||||
currentContextFile?: string,
|
||||
debugLogging?: boolean
|
||||
): {
|
||||
score: number;
|
||||
satisfiedLinks: number;
|
||||
@@ -362,14 +521,22 @@ function scoreAssignment(
|
||||
let satisfiedLinks = 0;
|
||||
let requiredLinks = normalized.links.length;
|
||||
const roleEvidence: Array<{ from: string; to: string; edgeRole: string; rawEdgeType: string }> = [];
|
||||
|
||||
|
||||
// Determine required_links: profile > template.matching > defaults.matching
|
||||
const requiredLinksEnabled = profile?.required_links ??
|
||||
template.matching?.required_links ??
|
||||
const requiredLinksEnabled = profile?.required_links ??
|
||||
template.matching?.required_links ??
|
||||
false;
|
||||
|
||||
|
||||
// Score slots filled
|
||||
score += assignment.size * 2;
|
||||
|
||||
// Small intra-note bonus so intra-note is preferred but cross-note can still reach top K (was +15, cross-note never made it)
|
||||
if (currentContextFile && assignment.size > 0) {
|
||||
const allSameFile = [...assignment.values()].every((n) => n.nodeKey.file === currentContextFile);
|
||||
if (allSameFile) {
|
||||
score += 5;
|
||||
}
|
||||
}
|
||||
|
||||
// Score links
|
||||
for (const link of normalized.links) {
|
||||
@@ -395,43 +562,78 @@ function scoreAssignment(
|
||||
edgeVocabulary,
|
||||
edgeTargetResolutionMap || new Map()
|
||||
);
|
||||
|
||||
const effectiveRole = edge?.edgeRole ?? (edge ? inferRoleFromRawType(edge.rawEdgeType, chainRoles) : null);
|
||||
|
||||
if (edge && edge.edgeRole) {
|
||||
// Check if edge role is allowed
|
||||
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))
|
||||
});
|
||||
|
||||
if (edge && effectiveRole) {
|
||||
if (!link.allowed_edge_roles || link.allowed_edge_roles.length === 0) {
|
||||
// No constraints = any role allowed
|
||||
score += 10;
|
||||
satisfiedLinks++;
|
||||
roleEvidence.push({
|
||||
from: link.from,
|
||||
to: link.to,
|
||||
edgeRole: edge.edgeRole,
|
||||
edgeRole: effectiveRole,
|
||||
rawEdgeType: edge.rawEdgeType,
|
||||
});
|
||||
} else if (link.allowed_edge_roles.includes(edge.edgeRole)) {
|
||||
} else if (link.allowed_edge_roles.includes(effectiveRole)) {
|
||||
score += 10;
|
||||
satisfiedLinks++;
|
||||
roleEvidence.push({
|
||||
from: link.from,
|
||||
to: link.to,
|
||||
edgeRole: edge.edgeRole,
|
||||
edgeRole: effectiveRole,
|
||||
rawEdgeType: edge.rawEdgeType,
|
||||
});
|
||||
} else if (requiredLinksEnabled) {
|
||||
score -= 5; // Penalty for wrong role on required link
|
||||
score -= 5;
|
||||
}
|
||||
} else {
|
||||
if (requiredLinksEnabled) {
|
||||
score -= 5;
|
||||
}
|
||||
if (debugLogging) {
|
||||
logLinkResolutionDiagnostic(
|
||||
link,
|
||||
fromKey,
|
||||
toKey,
|
||||
allEdges,
|
||||
edgeTargetResolutionMap || new Map(),
|
||||
chainRoles
|
||||
);
|
||||
}
|
||||
} else if (requiredLinksEnabled) {
|
||||
score -= 5; // Penalty for missing required link
|
||||
}
|
||||
}
|
||||
|
||||
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) => {
|
||||
const node = assignment.get(s.id);
|
||||
const headingNorm = node ? (normalizeHeadingForMatch(node.nodeKey.heading) ?? "") : "";
|
||||
return node ? `${s.id}:${node.nodeKey.file}:${headingNorm}` : `${s.id}:`;
|
||||
});
|
||||
return parts.sort().join("|");
|
||||
}
|
||||
|
||||
/**
|
||||
* Find best assignment for a template using backtracking.
|
||||
* Find top K distinct assignments for a template (e.g. intra-note and cross-note loop_learning).
|
||||
*/
|
||||
function findBestAssignment(
|
||||
function findTopKAssignments(
|
||||
template: ChainTemplate,
|
||||
normalized: { slots: ChainTemplateSlot[]; links: ChainTemplateLink[] },
|
||||
candidateNodes: CandidateNode[],
|
||||
@@ -441,25 +643,34 @@ function findBestAssignment(
|
||||
edgeVocabulary: EdgeVocabulary | null,
|
||||
profile?: TemplateMatchingProfile,
|
||||
edgeTargetResolutionMap?: Map<string, string>,
|
||||
templatesConfig?: ChainTemplatesConfig | null
|
||||
): TemplateMatch | null {
|
||||
templatesConfig?: ChainTemplatesConfig | null,
|
||||
currentContextFile?: string,
|
||||
topK: number = 2,
|
||||
debugLogging?: boolean
|
||||
): TemplateMatch[] {
|
||||
const slots = normalized.slots;
|
||||
if (slots.length === 0) return null;
|
||||
|
||||
// Filter candidates per slot
|
||||
if (slots.length === 0) return [];
|
||||
|
||||
const slotCandidates = new Map<string, CandidateNode[]>();
|
||||
for (const slot of slots) {
|
||||
const candidates = candidateNodes.filter((node) => nodeMatchesSlot(node, slot));
|
||||
slotCandidates.set(slot.id, candidates);
|
||||
}
|
||||
|
||||
// Backtracking assignment
|
||||
let bestMatch: TemplateMatch | null = null;
|
||||
let bestScore = -Infinity;
|
||||
|
||||
|
||||
if (debugLogging) {
|
||||
const slotSummary = slots.map((s) => {
|
||||
const cands = slotCandidates.get(s.id) || [];
|
||||
const files = [...new Set(cands.map((c) => c.nodeKey.file))].slice(0, 5);
|
||||
return `${s.id}=${cands.length}(${files.map((f) => f.split("/").pop() || f).join(",")}${cands.length > 5 ? "…" : ""})`;
|
||||
}).join("; ");
|
||||
getTemplateMatchingLogger().debug(`Template ${template.name}: slot candidates: ${slotSummary}`);
|
||||
}
|
||||
|
||||
type Collected = { assignment: Map<string, CandidateNode>; score: number; result: ReturnType<typeof scoreAssignment> };
|
||||
const collected: Collected[] = [];
|
||||
|
||||
function backtrack(assignment: Map<string, CandidateNode>, slotIndex: number) {
|
||||
if (slotIndex >= slots.length) {
|
||||
// Evaluate assignment
|
||||
const result = scoreAssignment(
|
||||
template,
|
||||
normalized,
|
||||
@@ -469,78 +680,150 @@ function findBestAssignment(
|
||||
chainRoles,
|
||||
edgeVocabulary,
|
||||
profile,
|
||||
edgeTargetResolutionMap
|
||||
edgeTargetResolutionMap,
|
||||
currentContextFile,
|
||||
debugLogging
|
||||
);
|
||||
|
||||
if (result.score > bestScore) {
|
||||
bestScore = result.score;
|
||||
const slotAssignments: TemplateMatch["slotAssignments"] = {};
|
||||
const missingSlots: string[] = [];
|
||||
|
||||
for (const slot of slots) {
|
||||
const node = assignment.get(slot.id);
|
||||
if (node) {
|
||||
slotAssignments[slot.id] = {
|
||||
nodeKey: `${node.nodeKey.file}:${node.nodeKey.heading || ""}`,
|
||||
file: node.nodeKey.file,
|
||||
heading: node.nodeKey.heading,
|
||||
noteType: node.noteType,
|
||||
};
|
||||
} else {
|
||||
missingSlots.push(slot.id);
|
||||
}
|
||||
if (collected.length < MAX_ASSIGNMENTS_COLLECTED) {
|
||||
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);
|
||||
const worst = collected[minIdx];
|
||||
if (worst != null && result.score > worst.score) {
|
||||
collected[minIdx] = { assignment: new Map(assignment), score: result.score, result };
|
||||
}
|
||||
|
||||
// Calculate completeness and confidence (will be set after matching)
|
||||
bestMatch = {
|
||||
templateName: template.name,
|
||||
score: result.score,
|
||||
slotAssignments,
|
||||
missingSlots,
|
||||
satisfiedLinks: result.satisfiedLinks,
|
||||
requiredLinks: result.requiredLinks,
|
||||
roleEvidence: result.roleEvidence.length > 0 ? result.roleEvidence : undefined,
|
||||
slotsComplete: false, // Will be set later
|
||||
linksComplete: false, // Will be set later
|
||||
confidence: "weak", // Will be set later
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
const slot = slots[slotIndex];
|
||||
if (!slot) return;
|
||||
|
||||
|
||||
const candidates = slotCandidates.get(slot.id) || [];
|
||||
|
||||
// Try each candidate
|
||||
|
||||
for (const candidate of candidates) {
|
||||
// Check if already assigned (no duplicates)
|
||||
let alreadyAssigned = false;
|
||||
for (const assignedNode of assignment.values()) {
|
||||
if (
|
||||
assignedNode.nodeKey.file === candidate.nodeKey.file &&
|
||||
assignedNode.nodeKey.heading === candidate.nodeKey.heading
|
||||
headingsMatch(assignedNode.nodeKey.heading, candidate.nodeKey.heading)
|
||||
) {
|
||||
alreadyAssigned = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!alreadyAssigned) {
|
||||
assignment.set(slot.id, candidate);
|
||||
backtrack(assignment, slotIndex + 1);
|
||||
assignment.delete(slot.id);
|
||||
}
|
||||
}
|
||||
|
||||
// Also try leaving slot unassigned
|
||||
|
||||
backtrack(assignment, slotIndex + 1);
|
||||
}
|
||||
|
||||
|
||||
backtrack(new Map(), 0);
|
||||
|
||||
return bestMatch;
|
||||
|
||||
collected.sort((a, b) => b.score - a.score);
|
||||
|
||||
const completeCount = collected.filter((c) => {
|
||||
let missing = 0;
|
||||
for (const slot of slots) {
|
||||
if (!c.assignment.get(slot.id)) missing++;
|
||||
}
|
||||
return missing === 0;
|
||||
}).length;
|
||||
|
||||
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[] = [];
|
||||
const seenSignatures = new Set<string>();
|
||||
|
||||
function pushMatch(
|
||||
assignment: Map<string, CandidateNode>,
|
||||
score: number,
|
||||
result: ReturnType<typeof scoreAssignment>
|
||||
): void {
|
||||
const slotAssignments: TemplateMatch["slotAssignments"] = {};
|
||||
const missingSlots: string[] = [];
|
||||
|
||||
for (const slot of slots) {
|
||||
const node = assignment.get(slot.id);
|
||||
if (node) {
|
||||
slotAssignments[slot.id] = {
|
||||
nodeKey: `${node.nodeKey.file}:${node.nodeKey.heading || ""}`,
|
||||
file: node.nodeKey.file,
|
||||
heading: node.nodeKey.heading,
|
||||
noteType: node.effectiveType,
|
||||
};
|
||||
} else {
|
||||
missingSlots.push(slot.id);
|
||||
}
|
||||
}
|
||||
|
||||
const sig = assignmentSignature(slots, assignment);
|
||||
if (seenSignatures.has(sig)) return;
|
||||
seenSignatures.add(sig);
|
||||
|
||||
out.push({
|
||||
templateName: template.name,
|
||||
score,
|
||||
slotAssignments,
|
||||
missingSlots,
|
||||
satisfiedLinks: result.satisfiedLinks,
|
||||
requiredLinks: result.requiredLinks,
|
||||
roleEvidence: result.roleEvidence.length > 0 ? result.roleEvidence : undefined,
|
||||
slotsComplete: false,
|
||||
linksComplete: false,
|
||||
confidence: "weak",
|
||||
});
|
||||
}
|
||||
|
||||
// Phase 1: add complete assignments (all slots filled) up to topK
|
||||
for (const { assignment, score, result } of collected) {
|
||||
if (out.length >= topK) break;
|
||||
const missingCount = slots.filter((s) => !assignment.get(s.id)).length;
|
||||
if (missingCount > 0) continue;
|
||||
pushMatch(assignment, score, result);
|
||||
}
|
||||
|
||||
// Phase 2: add incomplete assignments (some slots missing) until topK – chains are found even when not all slots can be filled
|
||||
for (const { assignment, score, result } of collected) {
|
||||
if (out.length >= topK) break;
|
||||
const missingCount = slots.filter((s) => !assignment.get(s.id)).length;
|
||||
if (missingCount === 0) continue;
|
||||
pushMatch(assignment, score, result);
|
||||
}
|
||||
|
||||
if (out.length > 0) {
|
||||
getTemplateMatchingLogger().debug(`--- Template ${template.name}: ${out.length} match(es) returned (these go into the report) ---`);
|
||||
let crossNoteCount = 0;
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
const m = out[i];
|
||||
if (!m) continue;
|
||||
const isCrossNote = currentContextFile
|
||||
? Object.values(m.slotAssignments).some((s) => s.file !== currentContextFile)
|
||||
: false;
|
||||
if (isCrossNote) crossNoteCount++;
|
||||
getTemplateMatchingLogger().debug(` #${i + 1} score=${m.score} links=${m.satisfiedLinks}/${m.requiredLinks}${isCrossNote ? " [cross-note]" : ""}`);
|
||||
for (const slot of slots) {
|
||||
const s = m.slotAssignments[slot.id];
|
||||
if (s) {
|
||||
const f = shortFile(s.file);
|
||||
const rawH = s.heading ?? "note";
|
||||
const h = rawH.length > 40 ? rawH.slice(0, 37) + "…" : rawH;
|
||||
getTemplateMatchingLogger().debug(` ${slot.id}: ${f}#${h}`);
|
||||
} else {
|
||||
getTemplateMatchingLogger().debug(` ${slot.id}: —`);
|
||||
}
|
||||
}
|
||||
}
|
||||
getTemplateMatchingLogger().debug(` Diversity: ${crossNoteCount} of ${out.length} match(es) use node(s) from another note (cross-note).`);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -579,7 +862,7 @@ export async function matchTemplates(
|
||||
templatesConfig: ChainTemplatesConfig | null,
|
||||
chainRoles: ChainRolesConfig | null,
|
||||
edgeVocabulary: EdgeVocabulary | null,
|
||||
options: { includeNoteLinks: boolean; includeCandidates: boolean },
|
||||
options: { includeNoteLinks: boolean; includeCandidates: boolean; maxMatchesPerTemplateDefault?: number; debugLogging?: boolean },
|
||||
profile?: TemplateMatchingProfile
|
||||
): Promise<TemplateMatch[]> {
|
||||
if (!templatesConfig || !templatesConfig.templates || templatesConfig.templates.length === 0) {
|
||||
@@ -587,12 +870,13 @@ export async function matchTemplates(
|
||||
}
|
||||
|
||||
// Build candidate nodes (with resolved paths)
|
||||
// No limit on nodes: process all nodes to ensure all edges are considered
|
||||
const candidateNodes = await buildCandidateNodes(
|
||||
app,
|
||||
currentContext,
|
||||
allEdges,
|
||||
options,
|
||||
30
|
||||
Number.MAX_SAFE_INTEGER
|
||||
);
|
||||
|
||||
// Create a map from original edge target to resolved path for edge matching
|
||||
@@ -609,13 +893,18 @@ export async function matchTemplates(
|
||||
return result.canonical;
|
||||
};
|
||||
|
||||
// Match each template
|
||||
// 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".
|
||||
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 matches: TemplateMatch[] = [];
|
||||
|
||||
|
||||
for (const template of templatesConfig.templates) {
|
||||
const normalized = normalizeTemplate(template, templatesConfig);
|
||||
|
||||
const match = findBestAssignment(
|
||||
|
||||
const templateMatches = findTopKAssignments(
|
||||
template,
|
||||
normalized,
|
||||
candidateNodes,
|
||||
@@ -625,13 +914,24 @@ export async function matchTemplates(
|
||||
edgeVocabulary,
|
||||
profile,
|
||||
edgeTargetResolutionMap,
|
||||
templatesConfig
|
||||
templatesConfig,
|
||||
currentContext.file,
|
||||
maxPerTemplate,
|
||||
options.debugLogging
|
||||
);
|
||||
|
||||
if (match) {
|
||||
|
||||
for (const match of templateMatches) {
|
||||
matches.push(match);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.debugLogging) {
|
||||
const byName: Record<string, number> = {};
|
||||
for (const m of matches) {
|
||||
byName[m.templateName] = (byName[m.templateName] ?? 0) + 1;
|
||||
}
|
||||
getTemplateMatchingLogger().info(`Template matching done: total=${matches.length} per_template=${JSON.stringify(byName)}`);
|
||||
}
|
||||
|
||||
// Calculate completeness and confidence for each match
|
||||
// Get causal-ish roles from config or use default
|
||||
@@ -656,7 +956,7 @@ export async function matchTemplates(
|
||||
match.confidence = "weak";
|
||||
} else {
|
||||
// Rule 2: slotsComplete=true
|
||||
const hasCausalRole = match.roleEvidence?.some((ev) => causalIshRoles.includes(ev.edgeRole)) ?? false;
|
||||
const hasCausalRole = match.roleEvidence?.some((ev: { edgeRole: string }) => causalIshRoles.includes(ev.edgeRole)) ?? false;
|
||||
|
||||
// If linksComplete=true AND there is at least one causal-ish role evidence => "confirmed"
|
||||
if (match.linksComplete && hasCausalRole) {
|
||||
@@ -669,13 +969,15 @@ export async function matchTemplates(
|
||||
}
|
||||
|
||||
// Sort by score desc, then name asc (deterministic)
|
||||
matches.sort((a, b) => {
|
||||
matches.sort((a: TemplateMatch, b: TemplateMatch) => {
|
||||
if (b.score !== a.score) {
|
||||
return b.score - a.score;
|
||||
}
|
||||
return a.templateName.localeCompare(b.templateName);
|
||||
});
|
||||
|
||||
// Keep top K (K=1 for v0)
|
||||
return matches.slice(0, 1);
|
||||
// Return all matches; chainInspector applies topN (maxTemplateMatches). Multiple chains
|
||||
// per note/section are supported (multiple templates); multiple matches per same template
|
||||
// would require findTopKAssignments per template (future).
|
||||
return matches;
|
||||
}
|
||||
Reference in new issue
Block a user