From e63a9e67ab2929f2ea1b078a1e5250d3ae561f17 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 1 Dec 2026 09:28:21 +1100 Subject: [PATCH] Add structured field, sourceKey, and line locations to validation issues --- bun.lock | 3 + package.json | 3 +- plugin/.claude-plugin/plugin.json | 2 +- plugin/types/index.d.ts | 9 ++ src/plugins/markdown/read-space.ts | 17 ++- src/plugins/markdown/util.ts | 51 ++++++++ src/plugins/util.ts | 2 + src/read/read-space.ts | 8 ++ src/types.ts | 11 ++ src/validate/format-errors.ts | 42 +++++- src/validate/index.ts | 14 +- src/validate/validate-graph.ts | 59 +++++++-- tests/validate/issue-locations.test.ts | 174 +++++++++++++++++++++++++ 13 files changed, 370 insertions(+), 25 deletions(-) create mode 100644 tests/validate/issue-locations.test.ts diff --git a/bun.lock b/bun.lock index eaad6f0b..4b85038b 100644 --- a/bun.lock +++ b/bun.lock @@ -21,6 +21,7 @@ "sctx-map-views": "^0.7.1", "unified": "^11.0.5", "unist-util-visit": "^5.1.0", + "yaml": "^2.9.1", }, "devDependencies": { "@anthropic-ai/claude-agent-sdk": "^0.3.310", @@ -597,6 +598,8 @@ "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], + "yargs": ["yargs@17.7.3", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g=="], "yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], diff --git a/package.json b/package.json index 38d7fa8f..162f13a4 100644 --- a/package.json +++ b/package.json @@ -88,6 +88,7 @@ "remark-parse": "^11.0.0", "sctx-map-views": "^0.7.1", "unified": "^11.0.5", - "unist-util-visit": "^5.1.0" + "unist-util-visit": "^5.1.0", + "yaml": "^2.9.1" } } diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 8c2d58f8..5fabea0d 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "structured-context", - "version": "0.27.5", + "version": "0.27.6", "description": "Structured content authoring for Obsidian — automatic validation hooks, slash commands, and agent skills to keep markdown files compliant with your schema.", "homepage": "https://github.com/mindsocket/structured-context", "repository": "https://github.com/mindsocket/structured-context", diff --git a/plugin/types/index.d.ts b/plugin/types/index.d.ts index 98a72a93..8881109d 100644 --- a/plugin/types/index.d.ts +++ b/plugin/types/index.d.ts @@ -71,6 +71,15 @@ export type IssueBase = { nodeId?: NodeId; /** The node's source, or the file a parse issue is about. */ source?: SourceLocation; + /** Structured location of the offending field within the node/file, when known. */ + location?: { + /** Canonical field as a JSON pointer into the node (e.g. `"/status"`, `"/links/0"`). */ + field?: string; + /** Key as written in the source file, before `fieldMap` remapping. */ + sourceKey?: string; + /** 1-based line number of that key/value in the source file. */ + line?: number; + }; }; /** One finding of a validation run. `kind` also selects the fields the issue carries. */ export type ValidationIssue = diff --git a/src/plugins/markdown/read-space.ts b/src/plugins/markdown/read-space.ts index 329ab014..c098151b 100644 --- a/src/plugins/markdown/read-space.ts +++ b/src/plugins/markdown/read-space.ts @@ -10,7 +10,14 @@ import type { MarkdownPluginConfig } from '.'; import { extractLinksFromAstNode, extractLinksFromFrontmatter, getEdgeFieldNames } from './extract-content-links'; import { extractEmbeddedNodes, ON_A_PAGE_TYPES } from './parse-embedded'; import { parseMarkdown } from './parse-markdown'; -import { applyFieldMap, defaultPageTitle, inferTypeFromPath, MATTER_OPTIONS, pathLinkTargets } from './util'; +import { + applyFieldMap, + defaultPageTitle, + extractYamlFieldSources, + inferTypeFromPath, + MATTER_OPTIONS, + pathLinkTargets, +} from './util'; type ReadSpaceDirectoryOptions = { includeOnAPageFiles?: boolean; @@ -119,6 +126,7 @@ export async function readSpaceDirectory( const nodes: BaseNode[] = []; const parseIssues: ParseIssue[] = []; const excludedPages: NonNullable = []; + const fieldSources: NonNullable = {}; const exclude = (file: string) => excludedPages.push({ source: { file }, linkTargets: pathLinkTargets(file) }); for (const file of files) { @@ -175,8 +183,12 @@ export async function readSpaceDirectory( const explicitTitle = typeof data.title === 'string' ? data.title : undefined; const title = explicitTitle ?? defaultPageTitle(file, mdCfg.folderIndex); const pathTargets = pathLinkTargets(file); - const fmMatch = content.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/); + const fmMatch = content.match(/^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); const lineOffset = fmMatch ? (fmMatch[0].match(/\n/g) || []).length : 0; + const nodeFieldSources = hasFrontmatter && fmMatch ? extractYamlFieldSources(fmMatch[1]!, 2, fieldMap) : undefined; + if (nodeFieldSources && Object.keys(nodeFieldSources).length > 0) { + fieldSources[file] = nodeFieldSources; + } // The page's links come from the whole body; embedded nodes take theirs from their own blocks of the same tree. const tree = parseMarkdown(parsed.content); @@ -225,6 +237,7 @@ export async function readSpaceDirectory( nodes, parseIssues, excludedPages, + ...(Object.keys(fieldSources).length > 0 ? { fieldSources } : {}), diagnostics: { kind: 'directory' }, ...(isPartial ? { partial: true } : {}), }; diff --git a/src/plugins/markdown/util.ts b/src/plugins/markdown/util.ts index e839875f..9a1de793 100644 --- a/src/plugins/markdown/util.ts +++ b/src/plugins/markdown/util.ts @@ -13,6 +13,7 @@ import { setTag, visit, } from 'js-yaml'; +import { isMap, isScalar, isSeq, LineCounter, parseDocument } from 'yaml'; import type { TypeInferenceConfig } from '.'; export function inferTypeFromPath( @@ -94,6 +95,56 @@ export function parseYaml(text: string): unknown { return load(text, { schema: YAML_SCHEMA }); } +function escapeJsonPointer(segment: string): string { + return segment.replace(/~/g, '~0').replace(/\//g, '~1'); +} + +/** + * Extract 1-based line numbers and original key names for YAML mapping keys and sequence items, + * keyed by canonical JSON pointer (with `fieldMap` applied to top-level keys). + */ +export function extractYamlFieldSources( + yamlText: string, + baseLine: number, + fieldMap?: Record, +): Record { + const result: Record = {}; + const lineCounter = new LineCounter(); + const doc = parseDocument(yamlText, { lineCounter }); + if (doc.errors.length > 0 || !doc.contents) return result; + + const lineOf = (node: { range?: [number, number, number] | null }): number | undefined => { + const start = node.range?.[0]; + return start !== undefined ? baseLine + lineCounter.linePos(start).line - 1 : undefined; + }; + + const walk = (node: unknown, prefix: string, sourceKey: string, depth: number): void => { + if (isMap(node)) { + for (const pair of node.items) { + if (!isScalar(pair.key) || pair.key.value == null) continue; + const rawKey = String(pair.key.value); + const canonicalKey = depth === 0 && fieldMap?.[rawKey] ? fieldMap[rawKey] : rawKey; + const pointer = `${prefix}/${escapeJsonPointer(canonicalKey)}`; + const line = lineOf(pair.key); + result[pointer] = { sourceKey: rawKey, ...(line !== undefined ? { line } : {}) }; + walk(pair.value, pointer, rawKey, depth + 1); + } + } else if (isSeq(node)) { + for (let i = 0; i < node.items.length; i++) { + const item = node.items[i] as { range?: [number, number, number] | null } | null; + if (!item) continue; + const pointer = `${prefix}/${i}`; + const line = lineOf(item); + result[pointer] = { sourceKey, ...(line !== undefined ? { line } : {}) }; + walk(item, pointer, sourceKey, depth + 1); + } + } + }; + + walk(doc.contents, '', '', 0); + return result; +} + export type DumpYamlOptions = DumpOptions & { replacer?: (key: string, value: unknown) => unknown; }; diff --git a/src/plugins/util.ts b/src/plugins/util.ts index f158a21d..e6044d95 100644 --- a/src/plugins/util.ts +++ b/src/plugins/util.ts @@ -61,6 +61,8 @@ export type ParseResult = { diagnostics: Record; /** True when the plugin honoured `options.files` and returned results for only those files. */ partial?: boolean; + /** Per-node field source positions keyed by node id then canonical JSON pointer (e.g. `"/status"`). */ + fieldSources?: Record>; }; export type ParseHook = (context: PluginContext, options?: ParseOptions) => Promise; diff --git a/src/read/read-space.ts b/src/read/read-space.ts index 096b4d4d..6227e2d5 100644 --- a/src/read/read-space.ts +++ b/src/read/read-space.ts @@ -25,6 +25,7 @@ function toReadSpaceResult( unresolvedRefs, unresolvedContentLinks, ...(result.excludedPages ? { excludedPages: result.excludedPages } : {}), + ...(result.fieldSources ? { fieldSources: result.fieldSources } : {}), }; } @@ -75,6 +76,12 @@ export async function refreshReadResult( const keptNodes: BaseNode[] = previous.nodes.filter( (n) => !n.source || !changedSet.has(normalizeFile(n.source.file)), ); + const keptIds = new Set(keptNodes.map((n) => String(n.id))); + const keptFieldSources: NonNullable = {}; + for (const [id, sources] of Object.entries(previous.fieldSources ?? {})) { + if (keptIds.has(id)) keptFieldSources[id] = sources; + } + const mergedFieldSources = { ...keptFieldSources, ...(result.fieldSources ?? {}) }; const keptParseIssues = previous.parseIssues.filter((i) => !changedSet.has(normalizeFile(i.source.file))); const keptExcludedPages = (previous.excludedPages ?? []).filter((p) => !changedSet.has(normalizeFile(p.source.file))); @@ -84,6 +91,7 @@ export async function refreshReadResult( nodes: [...keptNodes, ...result.nodes], parseIssues: [...keptParseIssues, ...result.parseIssues], excludedPages: [...keptExcludedPages, ...(result.excludedPages ?? [])], + ...(Object.keys(mergedFieldSources).length > 0 ? { fieldSources: mergedFieldSources } : {}), diagnostics: { ...previous.diagnostics, ...result.diagnostics }, }, context.schema.metadata, diff --git a/src/types.ts b/src/types.ts index 1942f7ae..806d7439 100644 --- a/src/types.ts +++ b/src/types.ts @@ -228,6 +228,8 @@ export type ReadSpaceResult = { unresolvedContentLinks: Array<{ nodeId: NodeId; target: string }>; /** Pages read but not made nodes, kept so incremental refreshes preserve content-link resolution. */ excludedPages?: Array>>; + /** Per-node field source positions keyed by node id then canonical JSON pointer (e.g. `"/status"`). */ + fieldSources?: Record>; }; export type SpaceContext = { @@ -274,6 +276,15 @@ type IssueBase = { nodeId?: NodeId; /** The node's source, or the file a parse issue is about. */ source?: SourceLocation; + /** Structured location of the offending field within the node/file, when known. */ + location?: { + /** Canonical field as a JSON pointer into the node (e.g. `"/status"`, `"/links/0"`). */ + field?: string; + /** Key as written in the source file, before `fieldMap` remapping. */ + sourceKey?: string; + /** 1-based line number of that key/value in the source file. */ + line?: number; + }; }; /** One finding of a validation run. `kind` also selects the fields the issue carries. */ diff --git a/src/validate/format-errors.ts b/src/validate/format-errors.ts index 26997691..ec3d4727 100644 --- a/src/validate/format-errors.ts +++ b/src/validate/format-errors.ts @@ -1,10 +1,45 @@ import type { ErrorObject } from 'ajv'; import { extractEntityInfo } from '../schema/schema'; -import type { SchemaWithMetadata } from '../types'; +import type { ReadSpaceResult, SchemaWithMetadata, ValidationIssue } from '../types'; interface FormattedError { message: string; dedupeKey: string; + field?: string; +} + +function escapeJsonPointer(segment: string): string { + return segment.replace(/~/g, '~0').replace(/\//g, '~1'); +} + +function fieldPointerFor(err: ErrorObject): string | undefined { + if (err.keyword === 'required' && typeof err.params?.missingProperty === 'string') { + return `${err.instancePath}/${escapeJsonPointer(err.params.missingProperty)}`; + } + if (err.keyword === 'additionalProperties' && typeof err.params?.additionalProperty === 'string') { + return `${err.instancePath}/${escapeJsonPointer(err.params.additionalProperty)}`; + } + return err.instancePath || undefined; +} + +/** Resolve a structured issue location from a canonical JSON pointer and a node's `fieldSources`. */ +export function resolveIssueLocation( + nodeFieldSources: NonNullable[string] | undefined, + field: string | undefined, +): ValidationIssue['location'] { + if (!field) return undefined; + const exact = nodeFieldSources?.[field]; + if (exact) return { field, ...exact }; + const topSegment = field.split('/')[1]; + const fallback = topSegment ? nodeFieldSources?.[`/${topSegment}`] : undefined; + if (fallback) { + return { + field, + sourceKey: fallback.sourceKey, + ...(fallback.line !== undefined ? { line: fallback.line } : {}), + }; + } + return { field }; } /** @@ -49,7 +84,7 @@ export function formatErrors( const key = `type:${validTypes.join(',')}`; if (!seen.has(key)) { seen.add(key); - formatted.push({ message, dedupeKey: key }); + formatted.push({ message, dedupeKey: key, field: '/type' }); } } } @@ -104,7 +139,8 @@ export function formatErrors( if (!seen.has(key)) { seen.add(key); - formatted.push({ message, dedupeKey: key }); + const field = fieldPointerFor(err); + formatted.push({ message, dedupeKey: key, ...(field ? { field } : {}) }); } } } diff --git a/src/validate/index.ts b/src/validate/index.ts index 25431af7..2f05bd90 100644 --- a/src/validate/index.ts +++ b/src/validate/index.ts @@ -23,7 +23,7 @@ import type { ValidateFileOutput, ValidationIssue, } from '../types'; -import { formatErrors } from './format-errors'; +import { formatErrors, resolveIssueLocation } from './format-errors'; import { validateGraph } from './validate-graph'; // ============================================================================ @@ -186,10 +186,10 @@ function toValidationOptions(context: SpaceContext, options: CommonValidateOptio export async function validateNodes( context: SpaceContext, nodes: SpaceNode[], - read: Pick, + read: Pick, options: ValidationOptions = {}, ): Promise { - const { unresolvedRefs } = read; + const { unresolvedRefs, fieldSources } = read; const { schema, schemaRefRegistry, schemaValidator } = context; const metadata = schema.metadata; @@ -206,6 +206,7 @@ export async function validateNodes( const at = node.source ? { source: node.source } : {}; if (canonicalType !== undefined && validTypes.length > 0 && !validTypes.includes(canonicalType)) { const sortedTypes = [...validTypes].sort(); + const location = resolveIssueLocation(fieldSources?.[node.id], '/type'); collected.add({ kind: 'schema', key: `schema:type:${sortedTypes.join(',')}`, @@ -213,6 +214,7 @@ export async function validateNodes( message: `Invalid type "${nodeType}". Valid types are: ${sortedTypes.join(', ')}`, nodeId: node.id, ...at, + ...(location ? { location } : {}), }); continue; } @@ -227,12 +229,13 @@ export async function validateNodes( if (validate(dataToValidate)) { validCount++; } else { - for (const { message, dedupeKey } of formatErrors( + for (const { message, dedupeKey, field } of formatErrors( validate.errors || [], schema, schemaRefRegistry, dataToValidate as Record, )) { + const location = resolveIssueLocation(fieldSources?.[node.id], field); collected.add({ kind: 'schema', key: `schema:${dedupeKey}`, @@ -240,6 +243,7 @@ export async function validateNodes( message, nodeId: node.id, ...at, + ...(location ? { location } : {}), }); } } @@ -248,7 +252,7 @@ export async function validateNodes( collected.addAll(findDuplicateIds(nodes)); // Validate all hierarchy constraints (field references and structure) - const hierarchyIssues = validateGraph(nodes, metadata, unresolvedRefs); + const hierarchyIssues = validateGraph(nodes, metadata, unresolvedRefs, fieldSources); collected.addAll(hierarchyIssues); const hierarchyFailureNodes = hierarchyIssues .filter((issue) => issue.kind === 'hierarchy') diff --git a/src/validate/validate-graph.ts b/src/validate/validate-graph.ts index f3c60292..5bba9e0f 100644 --- a/src/validate/validate-graph.ts +++ b/src/validate/validate-graph.ts @@ -1,5 +1,14 @@ import { resolveNodeType } from '../schema/schema'; -import type { Hierarchy, NodeId, SchemaMetadata, SpaceNode, UnresolvedRef, ValidationIssue } from '../types'; +import type { + Hierarchy, + NodeId, + ReadSpaceResult, + SchemaMetadata, + SpaceNode, + UnresolvedRef, + ValidationIssue, +} from '../types'; +import { resolveIssueLocation } from './format-errors'; /** A hierarchy issue's per-variant fields, keyed off the node and its parent. */ type HierarchyFields = Extract; @@ -8,7 +17,11 @@ function hierarchyIssue( at: { nodeId: NodeId; nodeType: string; nodeTitle: string }, via: { parentType: string; parentTitle: string }, description: string, + ownerNode: SpaceNode, + field: string, + fieldSources?: ReadSpaceResult['fieldSources'], ): HierarchyFields { + const location = resolveIssueLocation(fieldSources?.[ownerNode.id], `/${field}`); return { kind: 'hierarchy', key: `hierarchy:${description}`, @@ -16,6 +29,8 @@ function hierarchyIssue( message: description, ...at, ...via, + ...(ownerNode.source !== undefined && { source: ownerNode.source }), + ...(location ? { location } : {}), }; } @@ -27,18 +42,23 @@ export function validateGraph( nodes: SpaceNode[], metadata: SchemaMetadata, unresolvedRefs: UnresolvedRef[] = [], + fieldSources?: ReadSpaceResult['fieldSources'], ): ValidationIssue[] { - const brokenLinks: ValidationIssue[] = unresolvedRefs.map((u) => ({ - kind: 'broken-link' as const, - key: `broken-link:${u.ref}`, - severity: 'error', - message: `${u.ref} → ${u.message}`, - nodeId: u.id, - ...(u.source !== undefined && { source: u.source }), - ref: u.ref, - reason: u.message, - })); - return [...brokenLinks, ...validateHierarchyStructure(nodes, metadata)]; + const brokenLinks: ValidationIssue[] = unresolvedRefs.map((u) => { + const location = resolveIssueLocation(fieldSources?.[u.id], `/${u.field}`); + return { + kind: 'broken-link' as const, + key: `broken-link:${u.ref}`, + severity: 'error', + message: `${u.ref} → ${u.message}`, + nodeId: u.id, + ...(u.source !== undefined && { source: u.source }), + ...(location ? { location } : {}), + ref: u.ref, + reason: u.message, + }; + }); + return [...brokenLinks, ...validateHierarchyStructure(nodes, metadata, fieldSources)]; } /** @@ -50,7 +70,11 @@ export function validateGraph( * * Assumes resolveGraphEdges has already been called to populate node.resolvedParents. */ -export function validateHierarchyStructure(nodes: SpaceNode[], metadata: SchemaMetadata): HierarchyFields[] { +export function validateHierarchyStructure( + nodes: SpaceNode[], + metadata: SchemaMetadata, + fieldSources?: ReadSpaceResult['fieldSources'], +): HierarchyFields[] { const violations: HierarchyFields[] = []; const hierarchies = metadata.hierarchies ?? []; const relationships = metadata.relationships ?? []; @@ -123,6 +147,9 @@ export function validateHierarchyStructure(nodes: SpaceNode[], metadata: SchemaM { nodeId: parentNode.id, nodeType: parentType, nodeTitle: parentTitle }, { parentType: nodeType, parentTitle: nodeTitle }, `Invalid relationship: ${parentType} "${parentTitle}" has "${nodeTitle}" in field "${parentRef.field}" which is of type ${nodeType}, expected ${expected}`, + parentNode, + parentRef.field, + fieldSources, ), ); } @@ -136,6 +163,9 @@ export function validateHierarchyStructure(nodes: SpaceNode[], metadata: SchemaM { nodeId: node.id, nodeType, nodeTitle }, { parentType, parentTitle }, `Invalid relationship: ${nodeType} "${nodeTitle}" has "${parentTitle}" in field "${parentRef.field}" which is of type ${parentType}, expected ${expected}`, + node, + parentRef.field, + fieldSources, ), ); } @@ -172,6 +202,9 @@ export function validateHierarchyStructure(nodes: SpaceNode[], metadata: SchemaM { nodeId: node.id, nodeType, nodeTitle }, { parentType, parentTitle }, `Invalid parent: ${nodeType} "${nodeTitle}" cannot have ${parentType} "${parentTitle}" as parent`, + node, + parentRef.field, + fieldSources, ), ); } diff --git a/tests/validate/issue-locations.test.ts b/tests/validate/issue-locations.test.ts new file mode 100644 index 00000000..2bead1f1 --- /dev/null +++ b/tests/validate/issue-locations.test.ts @@ -0,0 +1,174 @@ +import { afterAll, describe, expect, it } from 'bun:test'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { Config } from '../../src/config'; +import { readSpace, refreshReadResult } from '../../src/read/read-space'; +import { createSpaceContext } from '../../src/space-context'; +import { validateNodes, validateSpace } from '../../src/validate'; +import { ofKind } from '../helpers/issues'; + +const META = + 'https://raw.githubusercontent.com/mindsocket/structured-context/main/schemas/generated/latest/_structured_context_schema_meta.json'; + +describe('structured issue locations', () => { + const dir = mkdtempSync(join(tmpdir(), 'sctx-issue-locations-')); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + const schemaPath = join(dir, 'schema.json'); + writeFileSync( + schemaPath, + JSON.stringify({ + $schema: META, + $id: 'sctx://issue-locations.test', + $metadata: { + hierarchy: { + levels: [{ type: 'goal' }, { type: 'task' }], + }, + }, + oneOf: [ + { + type: 'object', + properties: { + type: { const: 'goal' }, + title: { type: 'string' }, + }, + required: ['type', 'title'], + additionalProperties: false, + }, + { + type: 'object', + properties: { + type: { const: 'task' }, + title: { type: 'string' }, + status: { enum: ['open', 'done'] }, + parent: { type: 'string' }, + meta: { + type: 'object', + properties: { + priority: { type: 'integer' }, + }, + }, + tags: { + type: 'array', + items: { type: 'string' }, + }, + }, + required: ['type', 'title', 'status'], + additionalProperties: false, + }, + ], + }), + ); + + const space = join(dir, 'space'); + mkdirSync(space, { recursive: true }); + + writeFileSync(join(space, 'Goal.md'), ['---', 'record_type: goal', '---', ''].join('\n')); + + writeFileSync( + join(space, 'BadStatus.md'), + ['---', 'record_type: task', '"record_status": invalid', 'parent: "[[Missing]]"', '---', ''].join('\n'), + ); + + writeFileSync( + join(space, 'BadNested.md'), + ['---', 'record_type: task', 'record_status: open', 'meta: { priority: "high" }', '---', ''].join('\n'), + ); + + writeFileSync( + join(space, 'BadTag.md'), + ['---', 'record_type: task', 'record_status: open', 'tags:', ' - ok', ' - 42', '---', ''].join('\n'), + ); + + writeFileSync( + join(space, 'ExtraKey.md'), + ['---', 'record_type: task', 'record_status: open', 'extra_key: nope', '---', ''].join('\n'), + ); + + writeFileSync( + join(space, 'MissingRequired.md'), + ['---', 'record_type: task', 'parent: "[[BadStatus]]"', '---', ''].join('\n'), + ); + + writeFileSync(join(space, 'UnknownType.md'), ['---', '# comment', 'record_type: mystery', '---', ''].join('\n')); + + const config: Config = { + spaces: [ + { + name: 'loc', + path: space, + schema: schemaPath, + plugins: { + markdown: { + fieldMap: { + record_type: 'type', + record_status: 'status', + }, + }, + }, + }, + ], + }; + + it('populates field, sourceKey, and 1-based line across schema, broken-link, and hierarchy issues', async () => { + const ctx = createSpaceContext('loc', config, { configDir: dir }); + const result = await validateSpace(ctx); + + const schemaByNode = (id: string) => ofKind(result.issues, 'schema').filter((i) => String(i.nodeId) === id); + + // Unknown type with fieldMap reversal and comment line before it + const unknownIssues = schemaByNode('UnknownType.md'); + expect(unknownIssues).toHaveLength(1); + expect(unknownIssues[0]?.location).toEqual({ field: '/type', sourceKey: 'record_type', line: 3 }); + + // Quoted fieldMap key, flow-style nested key, array item, and additionalProperties + expect(schemaByNode('BadStatus.md')[0]?.location).toEqual({ + field: '/status', + sourceKey: 'record_status', + line: 3, + }); + expect(schemaByNode('BadNested.md')[0]?.location).toEqual({ + field: '/meta/priority', + sourceKey: 'priority', + line: 4, + }); + expect(schemaByNode('BadTag.md')[0]?.location).toEqual({ + field: '/tags/1', + sourceKey: 'tags', + line: 6, + }); + expect(schemaByNode('ExtraKey.md')[0]?.location).toEqual({ + field: '/extra_key', + sourceKey: 'extra_key', + line: 4, + }); + + // Missing required field has field pointer without line/sourceKey + expect(schemaByNode('MissingRequired.md')[0]?.location).toEqual({ field: '/status' }); + + // Broken link carries parent field location + const broken = ofKind(result.issues, 'broken-link').find((i) => String(i.nodeId) === 'BadStatus.md'); + expect(broken?.location).toEqual({ field: '/parent', sourceKey: 'parent', line: 4 }); + + // Hierarchy violation carries parent field location and source + const hierarchy = ofKind(result.issues, 'hierarchy').find((i) => String(i.nodeId) === 'MissingRequired.md'); + expect(hierarchy?.location).toEqual({ field: '/parent', sourceKey: 'parent', line: 3 }); + expect(hierarchy?.source).toEqual({ file: 'MissingRequired.md', line: 1 }); + }); + + it('updates fieldSources on incremental refresh', async () => { + const ctx = createSpaceContext('loc', config, { configDir: dir }); + const initial = await readSpace(ctx); + + writeFileSync( + join(space, 'UnknownType.md'), + ['---', '# line 2', '# line 3', 'record_type: mystery', '---', ''].join('\n'), + ); + + const refreshed = await refreshReadResult(ctx, initial, ['UnknownType.md']); + const result = await validateNodes(ctx, refreshed.nodes, refreshed); + const issue = ofKind(result.issues, 'schema').find((i) => String(i.nodeId) === 'UnknownType.md'); + expect(issue?.location).toEqual({ field: '/type', sourceKey: 'record_type', line: 4 }); + }); +});