Enhance Mindnet settings and chain inspection features
Node.js build / build (20.x) (push) Waiting to run
Node.js build / build (22.x) (push) Waiting to run

- Added new settings for analysis policies path, chain inspector include candidates, and max template matches.
- Updated MindnetSettingTab to allow user configuration of new settings with validation.
- Enhanced chain inspection logic to respect includeCandidates option consistently across findings.
- Improved template matching to apply slot type defaults for known templates, ensuring better handling of allowed node types.
- Refactored tests to validate new functionality and ensure consistent behavior in edge case scenarios.
This commit is contained in:
Lars committed 2026-01-19 15:47:23 +01:00
1 parent 3bb59afdda
commit 86c88bc275
15 files changed
+1867 -66

No files matched your search

+81 -27
View File
@@ -13,12 +13,14 @@ import { normalizeLinkTarget } from "../unresolvedLink/linkHelpers";
import type { EdgeVocabulary } from "../vocab/types";
import { parseEdgeVocabulary } from "../vocab/parseEdgeVocabulary";
import { VocabularyLoader } from "../vocab/VocabularyLoader";
import { applySeverityPolicy } from "./severityPolicy";
export interface InspectorOptions {
includeNoteLinks: boolean;
includeCandidates: boolean;
maxDepth: number;
direction: "forward" | "backward" | "both";
maxTemplateMatches?: number; // Optional: limit number of template matches (default: 3)
}
export interface Finding {
@@ -93,6 +95,7 @@ export interface ChainInspectorReport {
edgesWithCanonical: number;
edgesUnmapped: number;
roleMatches: { [roleName: string]: number };
topNUsed?: number;
};
templateMatches?: TemplateMatch[];
templatesSource?: {
@@ -490,9 +493,10 @@ function computeFindings(
};
// Count incoming edges (edges targeting current section)
// Use filterEdges to respect includeCandidates option (consistent with getNeighbors)
const filteredAllEdges = filterEdges(allEdges, options);
const incoming = filteredAllEdges.filter((edge) => {
if (edge.scope === "candidate") return false; // Exclude candidates
// 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 ||
(edge.target.heading === null && context.heading !== null);
@@ -500,17 +504,21 @@ function computeFindings(
});
// Count outgoing edges (edges originating from current section)
const outgoing = sectionEdges.filter((edge) => {
// Use filterEdges to respect includeCandidates option (consistent with getNeighbors)
// Note: sectionEdges already filters out candidates/note-level for missing_edges check,
// but for one_sided_connectivity we need to use the same filtering as getNeighbors
const filteredCurrentEdges = filterEdges(currentEdges, options);
const outgoing = filteredCurrentEdges.filter((edge) => {
const sourceMatches =
"sectionHeading" in edge.source
? edge.source.sectionHeading === context.heading &&
edge.source.file === context.file
: false;
: edge.scope === "note" && edge.source.file === context.file;
return sourceMatches;
});
// Debug logging for findings
console.log(`[Chain Inspector] computeFindings: incoming=${incoming.length}, outgoing=${outgoing.length}, allEdges=${allEdges.length}, filteredAllEdges=${filteredAllEdges.length}`);
// 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}`);
if (incoming.length > 0 && outgoing.length === 0) {
findings.push({
@@ -907,7 +915,14 @@ export async function inspectChains(
}
// Compute findings (use allEdges for incoming checks, currentEdges for outgoing checks)
const findings = computeFindings(
// Note: computeFindings will use filterEdges internally to respect includeCandidates,
// ensuring consistency with report.neighbors
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}`);
let findings = computeFindings(
allEdges, // Use allEdges so we can detect incoming edges from neighbor notes
currentEdges, // Use currentEdges for outgoing edge checks (only current note can have outgoing edges)
context,
@@ -953,13 +968,34 @@ export async function inspectChains(
}
}
const analysisMeta = {
let analysisMeta: ChainInspectorReport["analysisMeta"] = {
edgesTotal: filteredEdges.length,
edgesWithCanonical,
edgesUnmapped,
roleMatches: sortedRoleMatches,
};
// Resolve profile early (even if no templates) for logging
const profileName = templateMatchingProfileName || "discovery";
let profile: import("../dictionary/types").TemplateMatchingProfile | undefined;
let resolvedFrom: "settings" | "default" = "default";
if (chainTemplates?.defaults?.profiles) {
if (profileName === "discovery" && chainTemplates.defaults.profiles.discovery) {
profile = chainTemplates.defaults.profiles.discovery;
resolvedFrom = templateMatchingProfileName ? "settings" : "default";
} else if (profileName === "decisioning" && chainTemplates.defaults.profiles.decisioning) {
profile = chainTemplates.defaults.profiles.decisioning;
resolvedFrom = templateMatchingProfileName ? "settings" : "default";
}
}
// 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}`
);
// Template matching
let templateMatches: TemplateMatch[] = [];
let templatesSource: ChainInspectorReport["templatesSource"] = undefined;
@@ -973,21 +1009,6 @@ export async function inspectChains(
templateCount: templatesLoadResult.templateCount,
};
// Resolve profile from settings or defaults
const profileName = templateMatchingProfileName || "discovery";
let profile: import("../dictionary/types").TemplateMatchingProfile | undefined;
let resolvedFrom: "settings" | "default" = "default";
if (chainTemplates.defaults?.profiles) {
if (profileName === "discovery" && chainTemplates.defaults.profiles.discovery) {
profile = chainTemplates.defaults.profiles.discovery;
resolvedFrom = templateMatchingProfileName ? "settings" : "default";
} else if (profileName === "decisioning" && chainTemplates.defaults.profiles.decisioning) {
profile = chainTemplates.defaults.profiles.decisioning;
resolvedFrom = templateMatchingProfileName ? "settings" : "default";
}
}
// Set profile used info
templateMatchingProfileUsed = {
name: profileName,
@@ -1001,7 +1022,7 @@ export async function inspectChains(
try {
const { matchTemplates } = await import("./templateMatching");
templateMatches = await matchTemplates(
const allTemplateMatches = await matchTemplates(
app,
{ file: context.file, heading: context.heading },
allEdges,
@@ -1012,6 +1033,34 @@ export async function inspectChains(
profile
);
// Sort all matches: confidence rank (confirmed > plausible > weak), then score desc, then templateName asc
const confidenceRank = (c: "confirmed" | "plausible" | "weak"): number => {
if (c === "confirmed") return 3;
if (c === "plausible") return 2;
return 1; // weak
};
const sortedMatches = [...allTemplateMatches].sort((a, b) => {
// First by confidence rank (desc)
const rankDiff = confidenceRank(b.confidence) - confidenceRank(a.confidence);
if (rankDiff !== 0) return rankDiff;
// Then by score (desc)
if (b.score !== a.score) return b.score - a.score;
// Finally by templateName (asc)
return a.templateName.localeCompare(b.templateName);
});
// Limit to topN (default: 3, configurable via options.maxTemplateMatches)
const topN = options.maxTemplateMatches ?? 3;
templateMatches = sortedMatches.slice(0, topN);
// Store topNUsed in analysisMeta
if (analysisMeta) {
analysisMeta.topNUsed = topN;
}
// Add template-based findings with profile thresholds
for (const match of templateMatches) {
// missing_slot_<slotId> findings (with profile thresholds)
@@ -1025,7 +1074,7 @@ export async function inspectChains(
for (const slotId of match.missingSlots) {
findings.push({
code: `missing_slot_${slotId}`,
severity: "warn",
severity: applySeverityPolicy(profileName as "discovery" | "decisioning" | undefined, `missing_slot_${slotId}`, "warn"),
message: `Template ${match.templateName}: missing slot ${slotId} near current section`,
evidence: {
file: context.file,
@@ -1038,10 +1087,9 @@ export async function inspectChains(
// missing_link_constraints finding
if (match.slotsComplete && match.requiredLinks > 0 && !match.linksComplete) {
const severity = templateMatchingProfileName === "decisioning" ? "warn" : "info";
findings.push({
code: "missing_link_constraints",
severity,
severity: applySeverityPolicy(profileName as "discovery" | "decisioning" | undefined, "missing_link_constraints", "info"),
message: `Template ${match.templateName}: slots complete but link constraints missing (${match.satisfiedLinks}/${match.requiredLinks} satisfied)`,
evidence: {
file: context.file,
@@ -1058,7 +1106,7 @@ export async function inspectChains(
if (!hasCausalRole && match.satisfiedLinks > 0) {
findings.push({
code: "weak_chain_roles",
severity: "info",
severity: applySeverityPolicy(profileName as "discovery" | "decisioning" | undefined, "weak_chain_roles", "info"),
message: `Template ${match.templateName}: links satisfied but only by non-causal roles`,
evidence: {
file: context.file,
@@ -1073,6 +1121,12 @@ export async function inspectChains(
}
}
// Apply severity policy to all findings
findings = findings.map((finding) => ({
...finding,
severity: applySeverityPolicy(profileName as "discovery" | "decisioning" | undefined, finding.code, finding.severity),
}));
return {
context: {
file: context.file,
+51
View File
@@ -0,0 +1,51 @@
/**
* Centralized severity policy for Chain Inspector findings.
* Applies profile-aware severity rules.
*/
export type Severity = "info" | "warn" | "error";
export type ProfileName = "discovery" | "decisioning";
/**
* Apply severity policy based on profile and finding code.
*
* Policy rules:
* - missing_link_constraints:
* - discovery => INFO
* - decisioning => WARN
* - missing_slot_*:
* - discovery => INFO
* - decisioning => WARN
* - weak_chain_roles:
* - discovery => INFO
* - decisioning => INFO
* - All other findings: keep base severity (no change)
*/
export function applySeverityPolicy(
profileName: ProfileName | undefined,
findingCode: string,
baseSeverity: Severity
): Severity {
// If no profile specified, use base severity
if (!profileName) {
return baseSeverity;
}
// missing_link_constraints
if (findingCode === "missing_link_constraints") {
return profileName === "decisioning" ? "warn" : "info";
}
// missing_slot_*
if (findingCode.startsWith("missing_slot_")) {
return profileName === "decisioning" ? "warn" : "info";
}
// weak_chain_roles
if (findingCode === "weak_chain_roles") {
return "info"; // Always INFO for both profiles
}
// All other findings: keep base severity
return baseSeverity;
}
+67 -24
View File
@@ -93,19 +93,57 @@ function extractNoteType(markdown: string): string {
}
/**
* Normalize template to rich format.
* Known templates that should use slot_type_defaults when allowed_node_types is missing.
*/
function normalizeTemplate(template: ChainTemplate): {
const KNOWN_TEMPLATES_WITH_DEFAULTS = [
"trigger_transformation_outcome",
"decision_logic",
"loop_learning",
];
/**
* Normalize template to rich format.
* Applies slot_type_defaults for known templates when allowed_node_types is missing.
*/
function normalizeTemplate(
template: ChainTemplate,
templatesConfig?: ChainTemplatesConfig | null
): {
slots: ChainTemplateSlot[];
links: ChainTemplateLink[];
} {
// Normalize slots
const normalizedSlots: ChainTemplateSlot[] = [];
const slotTypeDefaults = templatesConfig?.defaults?.slot_type_defaults;
const isKnownTemplate = KNOWN_TEMPLATES_WITH_DEFAULTS.includes(template.name);
for (const slot of template.slots) {
if (typeof slot === "string") {
normalizedSlots.push({ id: slot });
// String slot: apply defaults if available and template is known
const slotId = slot;
let allowedTypes: string[] | undefined = undefined;
if (isKnownTemplate && slotTypeDefaults && slotTypeDefaults[slotId]) {
allowedTypes = slotTypeDefaults[slotId];
}
normalizedSlots.push({
id: slotId,
...(allowedTypes ? { allowed_node_types: allowedTypes } : {}),
});
} else {
normalizedSlots.push(slot);
// Rich slot: apply defaults if allowed_node_types is missing and template is known
const slotId = slot.id;
let allowedTypes = slot.allowed_node_types;
if (!allowedTypes && isKnownTemplate && slotTypeDefaults && slotTypeDefaults[slotId]) {
allowedTypes = slotTypeDefaults[slotId];
}
normalizedSlots.push({
...slot,
...(allowedTypes ? { allowed_node_types: allowedTypes } : {}),
});
}
}
@@ -244,16 +282,19 @@ function getEdgeRole(
/**
* Check if node matches slot constraints.
* Strict: if allowed_node_types is defined, node must match exactly.
*/
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
// 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.noteType);
// No constraints = any type allowed (permissive behavior for backward compatibility)
return true;
}
/**
@@ -399,7 +440,8 @@ function findBestAssignment(
chainRoles: ChainRolesConfig | null,
edgeVocabulary: EdgeVocabulary | null,
profile?: TemplateMatchingProfile,
edgeTargetResolutionMap?: Map<string, string>
edgeTargetResolutionMap?: Map<string, string>,
templatesConfig?: ChainTemplatesConfig | null
): TemplateMatch | null {
const slots = normalized.slots;
if (slots.length === 0) return null;
@@ -571,7 +613,7 @@ export async function matchTemplates(
const matches: TemplateMatch[] = [];
for (const template of templatesConfig.templates) {
const normalized = normalizeTemplate(template);
const normalized = normalizeTemplate(template, templatesConfig);
const match = findBestAssignment(
template,
@@ -582,7 +624,8 @@ export async function matchTemplates(
chainRoles,
edgeVocabulary,
profile,
edgeTargetResolutionMap
edgeTargetResolutionMap,
templatesConfig
);
if (match) {
@@ -600,7 +643,7 @@ export async function matchTemplates(
// Calculate linksComplete
const template = templatesConfig.templates.find((t) => t.name === match.templateName);
const normalized = template ? normalizeTemplate(template) : { slots: [], links: [] };
const normalized = template ? normalizeTemplate(template, templatesConfig) : { slots: [], links: [] };
if (normalized.links.length === 0) {
match.linksComplete = true; // No links means complete
} else {
@@ -608,20 +651,20 @@ export async function matchTemplates(
}
// Calculate confidence
const hasCausalRole = match.roleEvidence?.some((ev) => causalIshRoles.includes(ev.edgeRole)) ?? false;
const slotsFilled = Object.keys(match.slotAssignments).length;
const minSlotsFilled = profile?.min_slots_filled_for_gap_findings ?? 2;
const minScore = profile?.min_score_for_gap_findings ?? 0;
if (match.slotsComplete && match.linksComplete && hasCausalRole) {
match.confidence = "confirmed";
} else if (
(match.slotsComplete && (!match.linksComplete || !hasCausalRole)) ||
(slotsFilled >= minSlotsFilled && match.score >= minScore)
) {
match.confidence = "plausible";
} else {
// Rule 1: If slotsComplete is false => confidence MUST be "weak" (always)
if (!match.slotsComplete) {
match.confidence = "weak";
} else {
// Rule 2: slotsComplete=true
const hasCausalRole = match.roleEvidence?.some((ev) => causalIshRoles.includes(ev.edgeRole)) ?? false;
// If linksComplete=true AND there is at least one causal-ish role evidence => "confirmed"
if (match.linksComplete && hasCausalRole) {
match.confidence = "confirmed";
} else {
// Else => "plausible"
match.confidence = "plausible";
}
}
}