Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
2 changes: 1 addition & 1 deletion plugin/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
9 changes: 9 additions & 0 deletions plugin/types/index.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 15 additions & 2 deletions src/plugins/markdown/read-space.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -119,6 +126,7 @@ export async function readSpaceDirectory(
const nodes: BaseNode[] = [];
const parseIssues: ParseIssue[] = [];
const excludedPages: NonNullable<ParseResult['excludedPages']> = [];
const fieldSources: NonNullable<ParseResult['fieldSources']> = {};
const exclude = (file: string) => excludedPages.push({ source: { file }, linkTargets: pathLinkTargets(file) });

for (const file of files) {
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -225,6 +237,7 @@ export async function readSpaceDirectory(
nodes,
parseIssues,
excludedPages,
...(Object.keys(fieldSources).length > 0 ? { fieldSources } : {}),
diagnostics: { kind: 'directory' },
...(isPartial ? { partial: true } : {}),
};
Expand Down
51 changes: 51 additions & 0 deletions src/plugins/markdown/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Comment thread
mindsocket marked this conversation as resolved.
Resolved
yamlText: string,
baseLine: number,
fieldMap?: Record<string, string>,
): Record<string, { sourceKey: string; line?: number }> {
const result: Record<string, { sourceKey: string; line?: number }> = {};
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;
};
Expand Down
2 changes: 2 additions & 0 deletions src/plugins/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ export type ParseResult = {
diagnostics: Record<string, number | string | string[]>;
/** 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<string, Record<string, { sourceKey: string; line?: number }>>;
};

export type ParseHook = (context: PluginContext, options?: ParseOptions) => Promise<ParseResult | null>;
Expand Down
8 changes: 8 additions & 0 deletions src/read/read-space.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ function toReadSpaceResult(
unresolvedRefs,
unresolvedContentLinks,
...(result.excludedPages ? { excludedPages: result.excludedPages } : {}),
...(result.fieldSources ? { fieldSources: result.fieldSources } : {}),
};
}

Expand Down Expand Up @@ -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<ParseResult['fieldSources']> = {};
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)));

Expand All @@ -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,
Expand Down
11 changes: 11 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Required<Pick<BaseNode, 'source' | 'linkTargets'>>>;
/** Per-node field source positions keyed by node id then canonical JSON pointer (e.g. `"/status"`). */
fieldSources?: Record<string, Record<string, { sourceKey: string; line?: number }>>;
};

export type SpaceContext = {
Expand Down Expand Up @@ -274,6 +276,15 @@ type IssueBase<K extends ValidationIssueKind> = {
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. */
Expand Down
42 changes: 39 additions & 3 deletions src/validate/format-errors.ts
Original file line number Diff line number Diff line change
@@ -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<ReadSpaceResult['fieldSources']>[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 };
}

/**
Expand Down Expand Up @@ -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' });
}
}
}
Expand Down Expand Up @@ -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 } : {}) });
}
}
}
Expand Down
14 changes: 9 additions & 5 deletions src/validate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

// ============================================================================
Expand Down Expand Up @@ -186,10 +186,10 @@ function toValidationOptions(context: SpaceContext, options: CommonValidateOptio
export async function validateNodes(
context: SpaceContext,
nodes: SpaceNode[],
read: Pick<ReadSpaceResult, 'unresolvedRefs' | 'unresolvedContentLinks'>,
read: Pick<ReadSpaceResult, 'unresolvedRefs' | 'unresolvedContentLinks' | 'fieldSources'>,
options: ValidationOptions = {},
): Promise<ValidationResult> {
const { unresolvedRefs } = read;
const { unresolvedRefs, fieldSources } = read;
const { schema, schemaRefRegistry, schemaValidator } = context;
const metadata = schema.metadata;

Expand All @@ -206,13 +206,15 @@ 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(',')}`,
severity: 'error',
message: `Invalid type "${nodeType}". Valid types are: ${sortedTypes.join(', ')}`,
nodeId: node.id,
...at,
...(location ? { location } : {}),
});
continue;
}
Expand All @@ -227,19 +229,21 @@ 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<string, unknown>,
)) {
const location = resolveIssueLocation(fieldSources?.[node.id], field);
collected.add({
kind: 'schema',
key: `schema:${dedupeKey}`,
severity: 'error',
message,
nodeId: node.id,
...at,
...(location ? { location } : {}),
});
}
}
Expand All @@ -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')
Expand Down
Loading