Implement findings fixing and template matching features in Mindnet plugin
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run

- Added a new command to fix findings in the current section of a markdown file, enhancing user experience by automating issue resolution.
- Introduced settings for configuring actions related to missing notes and headings, allowing for customizable behavior during the fixing process.
- Enhanced the chain inspector to support template matching, providing users with insights into template utilization and potential gaps in their content.
- Updated the analysis report to include detailed metadata about edges and role matches, improving the clarity and usefulness of inspection results.
- Improved error handling and user notifications for fixing findings and template matching processes, ensuring better feedback during execution.
This commit is contained in:
Lars committed 2026-01-18 21:10:33 +01:00
1 parent b0efa32c66
commit 90ccec5f7d
26 files changed
+4536 -32

No files matched your search

+286 -12
View File
@@ -7,9 +7,12 @@ import { TFile } from "obsidian";
import type { SectionContext } from "./sectionContext";
import type { IndexedEdge, SectionNode } from "./graphIndex";
import { buildNoteIndex, loadNeighborNote } from "./graphIndex";
import type { ChainRolesConfig } from "../dictionary/types";
import type { ChainRolesConfig, ChainTemplatesConfig } from "../dictionary/types";
import { splitIntoSections } from "../mapping/sectionParser";
import { normalizeLinkTarget } from "../unresolvedLink/linkHelpers";
import type { EdgeVocabulary } from "../vocab/types";
import { parseEdgeVocabulary } from "../vocab/parseEdgeVocabulary";
import { VocabularyLoader } from "../vocab/VocabularyLoader";
export interface InspectorOptions {
includeNoteLinks: boolean;
@@ -44,6 +47,28 @@ export interface Path {
edges: Array<{ rawEdgeType: string; from: string; to: string }>;
}
export interface TemplateMatch {
templateName: string;
score: number;
slotAssignments: {
[slotId: string]: {
nodeKey: string;
file: string;
heading?: string | null;
noteType: string;
};
};
missingSlots: string[];
satisfiedLinks: number;
requiredLinks: number;
roleEvidence?: Array<{
from: string;
to: string;
edgeRole: string;
rawEdgeType: string;
}>;
}
export interface ChainInspectorReport {
context: {
file: string;
@@ -60,11 +85,50 @@ export interface ChainInspectorReport {
backward: Path[];
};
findings: Finding[];
analysisMeta?: {
edgesTotal: number;
edgesWithCanonical: number;
edgesUnmapped: number;
roleMatches: { [roleName: string]: number };
};
templateMatches?: TemplateMatch[];
templatesSource?: {
path: string;
status: "loaded" | "error" | "using-last-known-good";
loadedAt: number | null;
templateCount: number;
};
}
const MIN_TEXT_LENGTH_FOR_EDGE_CHECK = 200;
const CAUSAL_ROLE_NAMES = ["causal", "influences", "enables_constraints"];
/**
* Resolve canonical edge type from raw edge type using edge vocabulary.
*/
export function resolveCanonicalEdgeType(
rawEdgeType: string,
edgeVocabulary: EdgeVocabulary | null
): { canonical?: string; matchedBy: "canonical" | "alias" | "none" } {
if (!edgeVocabulary) {
return { matchedBy: "none" };
}
// Check if raw type is already canonical
if (edgeVocabulary.byCanonical.has(rawEdgeType)) {
return { canonical: rawEdgeType, matchedBy: "canonical" };
}
// Check if raw type is an alias (case-insensitive lookup)
const lowerRaw = rawEdgeType.toLowerCase();
const canonical = edgeVocabulary.aliasToCanonical.get(lowerRaw);
if (canonical) {
return { canonical, matchedBy: "alias" };
}
return { matchedBy: "none" };
}
/**
* Filter edges based on options.
*/
@@ -349,6 +413,8 @@ function computeFindings(
sections: SectionNode[],
sectionContent: string,
chainRoles: ChainRolesConfig | null,
edgeVocabulary: EdgeVocabulary | null,
app: App,
options: InspectorOptions
): Finding[] {
const findings: Finding[] = [];
@@ -478,18 +544,74 @@ function computeFindings(
}
// Check: dangling_target
const allTargets = new Set(
sectionEdges.map((e) => `${e.target.file}:${e.target.heading || ""}`)
);
// Note: We can't fully check if targets exist without loading all files,
// so we skip this for now or mark as "potential" if we have access to vault
// Check outgoing edges from current section for missing files/headings
for (const edge of sectionEdges) {
const targetFile = edge.target.file;
const targetHeading = edge.target.heading;
// Try to resolve target file
const resolvedFile = app.metadataCache.getFirstLinkpathDest(
normalizeLinkTarget(targetFile),
context.file
);
if (!resolvedFile) {
// File does not exist
const sourceHeading = "sectionHeading" in edge.source ? edge.source.sectionHeading : null;
findings.push({
code: "dangling_target",
severity: "error",
message: `Target file does not exist: ${targetFile}`,
evidence: {
file: context.file,
sectionHeading: sourceHeading,
},
});
continue;
}
// If heading is specified, check if it exists in the file
if (targetHeading !== null) {
const targetContent = app.metadataCache.getFileCache(resolvedFile);
if (targetContent) {
// Use file cache to check headings
const headings = targetContent.headings || [];
const headingExists = headings.some(
(h) => h.heading === targetHeading
);
if (!headingExists) {
const sourceHeading = "sectionHeading" in edge.source ? edge.source.sectionHeading : null;
findings.push({
code: "dangling_target_heading",
severity: "warn",
message: `Target heading not found in ${targetFile}: ${targetHeading}`,
evidence: {
file: context.file,
sectionHeading: sourceHeading,
},
});
}
} else {
// File cache not available - metadataCache might not have processed the file yet
// Skip heading check in this case (file exists but cache not ready)
// This is acceptable as metadataCache will eventually update
}
}
}
// Check: no_causal_roles (if chainRoles available)
// Use canonical types for role matching if edgeVocabulary is available
if (chainRoles) {
const hasCausalRole = sectionEdges.some((edge) => {
// First try canonical type if available
const { canonical } = resolveCanonicalEdgeType(edge.rawEdgeType, edgeVocabulary);
const edgeTypeToCheck = canonical || edge.rawEdgeType;
for (const [roleName, role] of Object.entries(chainRoles.roles)) {
if (CAUSAL_ROLE_NAMES.includes(roleName)) {
if (role.edge_types.includes(edge.rawEdgeType)) {
// Check both canonical and raw type (permissive)
if (role.edge_types.includes(edgeTypeToCheck) || role.edge_types.includes(edge.rawEdgeType)) {
return true;
}
}
@@ -529,7 +651,10 @@ export async function inspectChains(
app: App,
context: SectionContext,
options: InspectorOptions,
chainRoles: ChainRolesConfig | null
chainRoles: ChainRolesConfig | null,
edgeVocabularyPath?: string,
chainTemplates?: ChainTemplatesConfig | null,
templatesLoadResult?: { path: string; status: string; loadedAt: number | null; templateCount: number }
): Promise<ChainInspectorReport> {
// Build index for current note
const currentFile = app.vault.getAbstractFileByPath(context.file);
@@ -547,8 +672,15 @@ export async function inspectChains(
);
// Collect all outgoing targets to load neighbor notes
// Respect includeNoteLinks and includeCandidates toggles
const outgoingTargets = new Set<string>();
for (const edge of currentEdges) {
// Skip candidates if not included
if (edge.scope === "candidate" && !options.includeCandidates) continue;
// Skip note-level links if not included
if (edge.scope === "note" && !options.includeNoteLinks) continue;
// Only consider edges from current context
if (
("sectionHeading" in edge.source
? edge.source.sectionHeading === context.heading &&
@@ -631,24 +763,45 @@ export async function inspectChains(
// Load neighbor notes lazily to find incoming edges
const allEdges = [...currentEdges];
// Load outgoing targets (for forward paths)
// Resolve and deduplicate outgoing neighbor files
const outgoingNeighborFiles = new Set<string>(); // Use Set to deduplicate by resolved path
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}`);
for (const targetFile of outgoingTargets) {
if (targetFile === context.file) continue; // Skip self
const neighborFile = await loadNeighborNote(app, targetFile);
const neighborFile = await loadNeighborNote(app, targetFile, context.file);
if (neighborFile) {
const { edges: neighborEdges } = await buildNoteIndex(app, neighborFile);
const resolvedPath = neighborFile.path;
outgoingNeighborFiles.add(resolvedPath);
outgoingNeighborFileMap.set(targetFile, neighborFile);
}
}
// Load edges from outgoing neighbors
for (const neighborPath of outgoingNeighborFiles) {
const neighborFile = app.vault.getAbstractFileByPath(neighborPath);
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)`);
}
}
// Load notes that link to current note (for incoming edges and backward paths)
// 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`);
for (const sourceFile of notesLinkingToCurrent) {
if (sourceFile === context.file) continue; // Skip self
if (allNeighborFiles.has(sourceFile)) continue; // Skip if already loaded as outgoing neighbor
const sourceNoteFile = await loadNeighborNote(app, sourceFile);
const sourceNoteFile = await loadNeighborNote(app, sourceFile, context.file);
if (sourceNoteFile) {
allNeighborFiles.add(sourceNoteFile.path);
const { edges: sourceEdges } = await buildNoteIndex(app, sourceNoteFile);
console.log(`[Chain Inspector] Loaded ${sourceEdges.length} edges from ${sourceFile}`);
@@ -729,6 +882,17 @@ export async function inspectChains(
// Traverse paths (now includes edges from neighbor notes)
const paths = traversePaths(allEdges, context, options);
// Load edge vocabulary if path provided
let edgeVocabulary: EdgeVocabulary | null = null;
if (edgeVocabularyPath) {
try {
const vocabText = await VocabularyLoader.loadText(app, edgeVocabularyPath);
edgeVocabulary = parseEdgeVocabulary(vocabText);
} catch (error) {
console.warn(`[Chain Inspector] Could not load edge vocabulary from ${edgeVocabularyPath}:`, error);
}
}
// Compute findings (use allEdges for incoming checks, currentEdges for outgoing checks)
const findings = computeFindings(
allEdges, // Use allEdges so we can detect incoming edges from neighbor notes
@@ -737,9 +901,116 @@ export async function inspectChains(
sections,
currentSectionContent,
chainRoles,
edgeVocabulary,
app,
options
);
// Compute analysisMeta
const filteredEdges = filterEdges(allEdges, options);
let edgesWithCanonical = 0;
let edgesUnmapped = 0;
const roleMatches: { [roleName: string]: number } = {};
for (const edge of filteredEdges) {
const { canonical, matchedBy } = resolveCanonicalEdgeType(edge.rawEdgeType, edgeVocabulary);
if (matchedBy !== "none") {
edgesWithCanonical++;
} else {
edgesUnmapped++;
}
// Count role matches (using canonical if available)
if (chainRoles && canonical) {
for (const [roleName, role] of Object.entries(chainRoles.roles)) {
if (role.edge_types.includes(canonical)) {
roleMatches[roleName] = (roleMatches[roleName] || 0) + 1;
}
}
}
}
// Sort roleMatches keys for deterministic output
const sortedRoleMatches: { [roleName: string]: number } = {};
const sortedRoleNames = Object.keys(roleMatches).sort();
for (const roleName of sortedRoleNames) {
const count = roleMatches[roleName];
if (count !== undefined) {
sortedRoleMatches[roleName] = count;
}
}
const analysisMeta = {
edgesTotal: filteredEdges.length,
edgesWithCanonical,
edgesUnmapped,
roleMatches: sortedRoleMatches,
};
// Template matching
let templateMatches: TemplateMatch[] = [];
let templatesSource: ChainInspectorReport["templatesSource"] = undefined;
if (chainTemplates && templatesLoadResult) {
templatesSource = {
path: templatesLoadResult.path,
status: templatesLoadResult.status as "loaded" | "error" | "using-last-known-good",
loadedAt: templatesLoadResult.loadedAt,
templateCount: templatesLoadResult.templateCount,
};
try {
const { matchTemplates } = await import("./templateMatching");
templateMatches = await matchTemplates(
app,
{ file: context.file, heading: context.heading },
allEdges,
chainTemplates,
chainRoles,
edgeVocabulary,
options
);
// Add template-based findings
for (const match of templateMatches) {
// missing_slot_<slotId> findings
if (match.missingSlots.length > 0 && (match.score >= 0 || match.slotAssignments && Object.keys(match.slotAssignments).length >= 2)) {
for (const slotId of match.missingSlots) {
findings.push({
code: `missing_slot_${slotId}`,
severity: "warn",
message: `Template ${match.templateName}: missing slot ${slotId} near current section`,
evidence: {
file: context.file,
sectionHeading: context.heading,
},
});
}
}
// weak_chain_roles finding
if (match.roleEvidence && match.roleEvidence.length > 0) {
const hasCausalRole = match.roleEvidence.some((ev) =>
CAUSAL_ROLE_NAMES.includes(ev.edgeRole)
);
if (!hasCausalRole && match.satisfiedLinks > 0) {
findings.push({
code: "weak_chain_roles",
severity: "info",
message: `Template ${match.templateName}: links satisfied but only by non-causal roles`,
evidence: {
file: context.file,
sectionHeading: context.heading,
},
});
}
}
}
} catch (e) {
console.error("[Chain Inspector] Template matching failed:", e);
}
}
return {
context: {
file: context.file,
@@ -750,5 +1021,8 @@ export async function inspectChains(
neighbors,
paths,
findings,
analysisMeta,
templateMatches: templateMatches.length > 0 ? templateMatches : undefined,
templatesSource,
};
}
+17 -2
View File
@@ -130,15 +130,30 @@ export async function buildNoteIndex(
*/
export async function loadNeighborNote(
app: App,
targetFile: string
targetFile: string,
sourceFile?: string
): Promise<TFile | null> {
try {
// Try direct path first
const file = app.vault.getAbstractFileByPath(targetFile);
if (file instanceof TFile) {
return file;
}
} catch {
// File not found or not accessible
// File not found via direct path
}
// If not found and sourceFile provided, try resolving as wikilink
if (sourceFile) {
try {
const resolved = app.metadataCache.getFirstLinkpathDest(targetFile, sourceFile);
if (resolved && resolved instanceof TFile) {
return resolved;
}
} catch {
// Resolution failed
}
}
return null;
}
+594
View File
@@ -0,0 +1,594 @@
/**
* Chain Template Matching: Match templates against local subgraph.
*/
import type { App, TFile } from "obsidian";
import type { ChainTemplatesConfig, ChainTemplate, ChainTemplateSlot, ChainTemplateLink } from "../dictionary/types";
import type { ChainRolesConfig } from "../dictionary/types";
import type { IndexedEdge } from "./graphIndex";
import type { EdgeVocabulary } from "../vocab/types";
import { resolveCanonicalEdgeType } from "./chainInspector";
export interface NodeKey {
file: string;
heading: string | null;
}
export interface CandidateNode {
nodeKey: NodeKey;
noteType: string; // "unknown" if not found
}
export interface TemplateMatch {
templateName: string;
score: number;
slotAssignments: {
[slotId: string]: {
nodeKey: string;
file: string;
heading?: string | null;
noteType: string;
};
};
missingSlots: string[];
satisfiedLinks: number;
requiredLinks: number;
roleEvidence?: Array<{
from: string;
to: string;
edgeRole: string;
rawEdgeType: string;
}>;
}
const CAUSAL_ROLE_NAMES = ["causal", "influences", "enables_constraints"];
/**
* Extract note type from frontmatter.
*/
function extractNoteType(markdown: string): string {
const lines = markdown.split(/\r?\n/);
// Check if file starts with frontmatter delimiter
if (lines.length === 0 || lines[0]?.trim() !== "---") {
return "unknown";
}
// Find closing delimiter
let endIndex = -1;
for (let i = 1; i < lines.length; i++) {
const line = lines[i];
if (line && line.trim() === "---") {
endIndex = i;
break;
}
}
if (endIndex === -1) {
return "unknown";
}
// Parse YAML between delimiters
const frontmatterLines = lines.slice(1, endIndex);
const frontmatterText = frontmatterLines.join("\n");
// Match "type: value" or "type:value" (with optional quotes)
const typeMatch = frontmatterText.match(/^type\s*:\s*(.+)$/m);
if (!typeMatch || !typeMatch[1]) {
return "unknown";
}
let typeValue = typeMatch[1].trim();
// Remove quotes if present
if ((typeValue.startsWith('"') && typeValue.endsWith('"')) ||
(typeValue.startsWith("'") && typeValue.endsWith("'"))) {
typeValue = typeValue.slice(1, -1);
}
return String(typeValue);
}
/**
* Normalize template to rich format.
*/
function normalizeTemplate(template: ChainTemplate): {
slots: ChainTemplateSlot[];
links: ChainTemplateLink[];
} {
// Normalize slots
const normalizedSlots: ChainTemplateSlot[] = [];
for (const slot of template.slots) {
if (typeof slot === "string") {
normalizedSlots.push({ id: slot });
} else {
normalizedSlots.push(slot);
}
}
// Normalize links
const normalizedLinks: ChainTemplateLink[] = template.links || [];
return { slots: normalizedSlots, links: normalizedLinks };
}
/**
* Build candidate node set from edges.
*/
async function buildCandidateNodes(
app: App,
currentContext: { file: string; heading: string | null },
allEdges: IndexedEdge[],
options: { includeNoteLinks: boolean; includeCandidates: boolean },
maxNodes: number = 30
): Promise<CandidateNode[]> {
const nodeKeys = new Set<string>();
const nodeMap = new Map<string, CandidateNode>();
// Add current context node
const currentKey = `${currentContext.file}:${currentContext.heading || ""}`;
nodeKeys.add(currentKey);
// Add all target nodes from edges
for (const edge of allEdges) {
if (edge.scope === "candidate" && !options.includeCandidates) continue;
if (edge.scope === "note" && !options.includeNoteLinks) continue;
const targetKey = `${edge.target.file}:${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 || ""}`;
nodeKeys.add(sourceKey);
} else {
const sourceKey = `${edge.source.file}:`;
nodeKeys.add(sourceKey);
}
}
// Limit to maxNodes (deterministic sorting)
const sortedKeys = Array.from(nodeKeys).sort();
const limitedKeys = sortedKeys.slice(0, maxNodes);
// Load note types for each node
const candidateNodes: CandidateNode[] = [];
const fileCache = new Map<string, string>(); // resolved file path -> noteType
const pathResolutionCache = new Map<string, string | null>(); // original file -> resolved path
for (const key of limitedKeys) {
const [file, heading] = key.split(":");
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;
resolvedPath = resolved.path;
} else {
resolvedPath = null;
}
} else if (fileObj && "path" in fileObj) {
resolvedPath = fileObj.path;
} else {
resolvedPath = null;
}
pathResolutionCache.set(file, resolvedPath);
}
if (!resolvedPath) {
// File not found, skip this node
continue;
}
// Get note type (cache per resolved file path)
let noteType = fileCache.get(resolvedPath);
if (noteType === 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);
} else {
noteType = "unknown";
}
} catch {
noteType = "unknown";
}
fileCache.set(resolvedPath, noteType);
}
candidateNodes.push({
nodeKey: { file: resolvedPath, heading: heading || null },
noteType,
});
}
return candidateNodes;
}
/**
* Get edge role for an edge using chain roles config.
*/
function getEdgeRole(
rawEdgeType: string,
canonicalEdgeType: string | undefined,
chainRoles: ChainRolesConfig | null
): string | null {
if (!chainRoles) return null;
const edgeTypeToCheck = canonicalEdgeType || rawEdgeType;
// Check both canonical and raw type (permissive)
for (const [roleName, role] of Object.entries(chainRoles.roles)) {
if (role.edge_types.includes(edgeTypeToCheck) || role.edge_types.includes(rawEdgeType)) {
return roleName;
}
}
return null;
}
/**
* Check if node matches slot constraints.
*/
function nodeMatchesSlot(
node: CandidateNode,
slot: ChainTemplateSlot
): boolean {
if (!slot.allowed_node_types || slot.allowed_node_types.length === 0) {
return true; // No constraints = any type allowed
}
return slot.allowed_node_types.includes(node.noteType);
}
/**
* Find edge between two nodes.
* Uses resolved paths from candidate nodes and edge target resolution map.
*/
function findEdgeBetween(
fromKey: string,
toKey: string,
allEdges: IndexedEdge[],
canonicalEdgeType: (rawType: string) => string | undefined,
chainRoles: ChainRolesConfig | null,
edgeVocabulary: EdgeVocabulary | null,
edgeTargetResolutionMap: Map<string, string>
): { edgeRole: string | null; rawEdgeType: string } | null {
const [fromFile, fromHeading] = fromKey.split(":");
const [toFile, toHeading] = toKey.split(":");
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 canonical = canonicalEdgeType(edge.rawEdgeType);
const edgeRole = getEdgeRole(edge.rawEdgeType, canonical, chainRoles);
return { edgeRole, rawEdgeType: edge.rawEdgeType };
}
}
return null;
}
/**
* Score assignment for template matching.
*/
function scoreAssignment(
template: ChainTemplate,
normalized: { slots: ChainTemplateSlot[]; links: ChainTemplateLink[] },
assignment: Map<string, CandidateNode>,
allEdges: IndexedEdge[],
canonicalEdgeType: (rawType: string) => string | undefined,
chainRoles: ChainRolesConfig | null,
edgeVocabulary: EdgeVocabulary | null,
defaultsRequiredLinks?: boolean,
edgeTargetResolutionMap?: Map<string, string>
): {
score: number;
satisfiedLinks: number;
requiredLinks: number;
roleEvidence: Array<{ from: string; to: string; edgeRole: string; rawEdgeType: string }>;
} {
let score = 0;
let satisfiedLinks = 0;
let requiredLinks = normalized.links.length;
const roleEvidence: Array<{ from: string; to: string; edgeRole: string; rawEdgeType: string }> = [];
const requiredLinksEnabled = template.matching?.required_links ?? defaultsRequiredLinks ?? false;
// Score slots filled
score += assignment.size * 2;
// Score links
for (const link of normalized.links) {
const fromNode = assignment.get(link.from);
const toNode = assignment.get(link.to);
if (!fromNode || !toNode) {
if (requiredLinksEnabled) {
score -= 5; // Penalty for missing required link
}
continue;
}
const fromKey = `${fromNode.nodeKey.file}:${fromNode.nodeKey.heading || ""}`;
const toKey = `${toNode.nodeKey.file}:${toNode.nodeKey.heading || ""}`;
const edge = findEdgeBetween(
fromKey,
toKey,
allEdges,
canonicalEdgeType,
chainRoles,
edgeVocabulary,
edgeTargetResolutionMap || new Map()
);
if (edge && edge.edgeRole) {
// Check if edge role is allowed
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,
rawEdgeType: edge.rawEdgeType,
});
} else if (link.allowed_edge_roles.includes(edge.edgeRole)) {
score += 10;
satisfiedLinks++;
roleEvidence.push({
from: link.from,
to: link.to,
edgeRole: edge.edgeRole,
rawEdgeType: edge.rawEdgeType,
});
} else if (requiredLinksEnabled) {
score -= 5; // Penalty for wrong role on required link
}
} else if (requiredLinksEnabled) {
score -= 5; // Penalty for missing required link
}
}
return { score, satisfiedLinks, requiredLinks, roleEvidence };
}
/**
* Find best assignment for a template using backtracking.
*/
function findBestAssignment(
template: ChainTemplate,
normalized: { slots: ChainTemplateSlot[]; links: ChainTemplateLink[] },
candidateNodes: CandidateNode[],
allEdges: IndexedEdge[],
canonicalEdgeType: (rawType: string) => string | undefined,
chainRoles: ChainRolesConfig | null,
edgeVocabulary: EdgeVocabulary | null,
defaultsRequiredLinks?: boolean,
edgeTargetResolutionMap?: Map<string, string>
): TemplateMatch | null {
const slots = normalized.slots;
if (slots.length === 0) return null;
// Filter candidates per slot
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;
function backtrack(assignment: Map<string, CandidateNode>, slotIndex: number) {
if (slotIndex >= slots.length) {
// Evaluate assignment
const result = scoreAssignment(
template,
normalized,
assignment,
allEdges,
canonicalEdgeType,
chainRoles,
edgeVocabulary,
defaultsRequiredLinks,
edgeTargetResolutionMap
);
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);
}
}
bestMatch = {
templateName: template.name,
score: result.score,
slotAssignments,
missingSlots,
satisfiedLinks: result.satisfiedLinks,
requiredLinks: result.requiredLinks,
roleEvidence: result.roleEvidence.length > 0 ? result.roleEvidence : undefined,
};
}
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
) {
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;
}
/**
* Resolve edge target to full path.
*/
function resolveEdgeTargetPath(
app: App,
targetFile: string,
sourceFile: string
): string {
// If already a full path, return as is
if (targetFile.includes("/") || targetFile.endsWith(".md")) {
const fileObj = app.vault.getAbstractFileByPath(targetFile);
if (fileObj && "path" in fileObj) {
return fileObj.path;
}
}
// Try to resolve as wikilink
const resolved = app.metadataCache.getFirstLinkpathDest(targetFile, sourceFile);
if (resolved) {
return resolved.path;
}
// Fallback: return original (will be handled as "unknown" type)
return targetFile;
}
/**
* Match templates against local subgraph.
*/
export async function matchTemplates(
app: App,
currentContext: { file: string; heading: string | null },
allEdges: IndexedEdge[],
templatesConfig: ChainTemplatesConfig | null,
chainRoles: ChainRolesConfig | null,
edgeVocabulary: EdgeVocabulary | null,
options: { includeNoteLinks: boolean; includeCandidates: boolean }
): Promise<TemplateMatch[]> {
if (!templatesConfig || !templatesConfig.templates || templatesConfig.templates.length === 0) {
return [];
}
// Build candidate nodes (with resolved paths)
const candidateNodes = await buildCandidateNodes(
app,
currentContext,
allEdges,
options,
30
);
// Create a map from original edge target to resolved path for edge matching
const edgeTargetResolutionMap = new Map<string, string>();
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);
}
// Create canonical edge type resolver
const canonicalEdgeType = (rawType: string): string | undefined => {
const result = resolveCanonicalEdgeType(rawType, edgeVocabulary);
return result.canonical;
};
const defaultsRequiredLinks = templatesConfig.defaults?.matching?.required_links;
// Match each template
const matches: TemplateMatch[] = [];
for (const template of templatesConfig.templates) {
const normalized = normalizeTemplate(template);
const match = findBestAssignment(
template,
normalized,
candidateNodes,
allEdges,
canonicalEdgeType,
chainRoles,
edgeVocabulary,
defaultsRequiredLinks,
edgeTargetResolutionMap
);
if (match) {
matches.push(match);
}
}
// Sort by score desc, then name asc (deterministic)
matches.sort((a, b) => {
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);
}