Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): report OKF frontmatter problems on the WYSIWYG affordances (PRD-8131) (#3670)

serafin-garcia456497da4084
diff --git a/.changeset/okf-frontmatter-wysiwyg-affordances.md b/.changeset/okf-frontmatter-wysiwyg-affordances.md
new file mode 100644
index 000000000..a304fc577
--- /dev/null
+++ b/.changeset/okf-frontmatter-wysiwyg-affordances.md
@@ -0,0 +1,7 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+OKF frontmatter problems now appear on the WYSIWYG affordances. The Add-properties badge counts them and stages a pre-named row for a missing required property (`type` included), the add-property field picker offers the OKF profile's declared fields with their required hints and descriptions, and the property panel's invalid count includes OKF shape violations, all respecting per-rule toggles and the profile's doc scoping, and working with OKF enabled on its own. On a document with no frontmatter region, an OKF frontmatter violation no longer paints a squiggle on the first body block, and clicking its Problems-panel row no longer scrolls to that block. The property panel owns the error, exactly as it already did for the built-in frontmatter plugin. OKF body rules are untouched: they keep their block decorations and row navigation.
+
+The add-property field picker also stops offering fields no widget can author conformantly. This applies to every governing schema, user-authored ones included, not just the OKF profile: a field whose only constraint is `anyOf` / `oneOf` / `allOf` / `not`, or an array whose items are objects, is withdrawn, because committing the row the picker suggested would immediately be faulted by the schema that suggested it. A field a schema REQUIRES stays offered whatever its shape, since the missing-property diagnostic stages a row for it either way, and it keeps its schema description.
diff --git a/packages/app/src/components/EditorToolbar.dom.test.tsx b/packages/app/src/components/EditorToolbar.dom.test.tsx
index 287f825da..6b150822f 100644
--- a/packages/app/src/components/EditorToolbar.dom.test.tsx
+++ b/packages/app/src/components/EditorToolbar.dom.test.tsx
@@ -217,4 +217,25 @@ describe('EditorToolbar runtime layout', () => {
expect((await screen.findByTestId('add-properties-problem-badge')).textContent).toBe('2');
});
+
+ test('two schemas requiring one property badge once and list it once', async () => {
+ // Composed the way EditorArea feeds this prop, because that is where the
+ // per-property collapse happens — two producers each requiring `type` (an
+ // OKF profile beside a project's own schema) is one row to add, and the
+ // tooltip promises exactly what the click will stage.
+ const { partitionFrontmatterProblems } = await import('@/editor/useFrontmatterDiagnostics');
+ const user = userEvent.setup();
+ const bothRequireType = [
+ { ...missing('type'), source: 'okf' as const, code: 'frontmatter-required' },
+ missing('type'),
+ ];
+ await renderToolbar('docs/Page.md', partitionFrontmatterProblems(bothRequireType).missing);
+
+ expect((await screen.findByTestId('add-properties-problem-badge')).textContent).toBe('1');
+
+ await user.hover(screen.getByTestId('add-properties-button'));
+ const tooltip = await screen.findByRole('tooltip');
+ const rows = tooltip.textContent?.split('Frontmatter property "type" is required').length;
+ expect(rows).toBe(2);
+ });
});
diff --git a/packages/app/src/components/ProblemsPanel.okf-nav.dom.test.tsx b/packages/app/src/components/ProblemsPanel.okf-nav.dom.test.tsx
new file mode 100644
index 000000000..73acf22d6
--- /dev/null
+++ b/packages/app/src/components/ProblemsPanel.okf-nav.dom.test.tsx
@@ -0,0 +1,107 @@
+/**
+ * The Problems-row navigation detail produced by the panel itself, fed a REAL
+ * OKF frontmatter diagnostic from the real lint engine. The sibling suite only
+ * ever clicks hand-built diagnostics and asserts the detail's existing fields,
+ * so it cannot notice when the panel drops a field the WYSIWYG consumer needs.
+ *
+ * The contract under test: a row click must dispatch a `LINT_NAV_EVENT` whose
+ * detail carries the diagnostic's `frontmatterScope` alongside the existing
+ * docName/line/column/source fields. The WYSIWYG editor declines navigation by
+ * that scope metadata (a frontmatter violation has no body anchor); a detail
+ * that omits it makes the consumer fall back to plugin identity, which admits
+ * OKF's frontmatter findings into body navigation.
+ */
+
+import { type LinterConfig, lintDocument } from '@inkeep/open-knowledge-core';
+import { cleanup, fireEvent, render as rtlRender, screen } from '@testing-library/react';
+import type { ReactElement } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { DiagnosticLike, LintNavDetail } from './ProblemsPanel';
+
+// Mocked at the HTTP boundary exactly as the sibling suite does: the panel
+// fetches the effective lint config and (in project scope) the audit plane on
+// mount/activation, and this test exercises neither surface.
+vi.doMock('@/editor/lint-config-client', () => ({
+ emitLintConfigChanged: () => {},
+ subscribeToLintConfigChanged: () => () => {},
+ fixLintDoc: async () => ({ ok: true }),
+ useDocLintConfig: () => ({ data: null }),
+ useProjectLintConfig: () => ({ data: null }),
+ fetchEffectiveLintConfig: async () => null,
+ writeMarkdownlintRule: async () => ({ ok: false, errorDetail: null }),
+}));
+vi.doMock('@/editor/validation-audit-client', () => ({
+ AUDIT_SUPERSEDED: 'audit-superseded',
+ runValidationAudit: async () => null,
+ useDocLinkFindings: () => ({ status: 'loaded', findings: [] }),
+}));
+
+const { ProblemsPanel, LINT_NAV_EVENT } = await import('./ProblemsPanel');
+const { clearPendingSourceNavigationsForTest } = await import('@/editor/source-editor-navigation');
+
+// A concept-scoped doc name (anything but a reserved `index`/`log` filename),
+// matching the OKF recommended schemas' appliesTo scoping.
+const DOC_NAME = 'usability-sessions/kenny/notes/serafin';
+
+// OKF alone: the engine's frontmatter-required rule is the only producer here,
+// so the panel renders exactly one row and the click target is unambiguous.
+const config: LinterConfig = {
+ enabled: true,
+ plugins: {
+ markdownlint: { enabled: false, rules: {} },
+ frontmatter: { enabled: false, schemas: [] },
+ okf: { enabled: true },
+ },
+};
+
+afterEach(() => {
+ cleanup();
+ clearPendingSourceNavigationsForTest();
+});
+
+/** Production mounts the panel under main.tsx's root TooltipProvider. */
+function render(ui: ReactElement) {
+ return rtlRender(<TooltipProvider>{ui}</TooltipProvider>);
+}
+
+describe('ProblemsPanel navigation detail for a real OKF frontmatter diagnostic', () => {
+ test('a row click dispatches a detail carrying the diagnostic frontmatterScope', async () => {
+ // Frontmatter present but missing the required `type` property.
+ const text = '---\ntitle: Serafin\ndescription: Session notes\ntags: []\n---\n\nSome notes.\n';
+ const diagnostics: DiagnosticLike[] = await lintDocument(text, config, DOC_NAME);
+
+ // Producer half of the contract (already upheld): the real engine emits the
+ // violation scope-tagged. If these fail, the fixture broke — not the panel.
+ const produced = diagnostics.find(
+ (d) => d.source === 'okf' && d.code === 'frontmatter-required',
+ );
+ expect(produced?.frontmatterScope).toBe('missing');
+ expect(produced?.frontmatterProperty).toBe('type');
+
+ // Consumer half: the panel's own detail must carry that scope forward.
+ // `frontmatterScope` is asserted through the diagnostic's wire shape so the
+ // expectation stays valid whether or not `LintNavDetail` declares it yet.
+ let received: (LintNavDetail & Pick<DiagnosticLike, 'frontmatterScope'>) | null = null;
+ const listener = (e: Event) => {
+ received = (e as CustomEvent<LintNavDetail>).detail;
+ };
+ window.addEventListener(LINT_NAV_EVENT, listener);
+ try {
+ render(<ProblemsPanel docName={DOC_NAME} diagnostics={diagnostics} />);
+ fireEvent.click(screen.getByRole('button'));
+ expect(received).not.toBeNull();
+ // toMatchObject, not toEqual: the detail may legitimately carry further
+ // diagnostic metadata (e.g. the property name) beyond this contract.
+ expect(received).toMatchObject({
+ docName: DOC_NAME,
+ line: (produced?.range.start.line ?? Number.NaN) + 1,
+ column: (produced?.range.start.character ?? Number.NaN) + 1,
+ source: 'okf',
+ frontmatterScope: 'missing',
+ });
+ } finally {
+ window.removeEventListener(LINT_NAV_EVENT, listener);
+ }
+ });
+});
diff --git a/packages/app/src/components/ProblemsPanel.tsx b/packages/app/src/components/ProblemsPanel.tsx
index 24e6e2d35..11f5cdc50 100644
--- a/packages/app/src/components/ProblemsPanel.tsx
+++ b/packages/app/src/components/ProblemsPanel.tsx
@@ -1,6 +1,10 @@
// biome-ignore-all lint/plugin/no-raw-html-interactive-element: matches sibling OutlinePanel — positional list of <button> rows awaiting a shared shadcn list primitive; tracked at https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit
// biome-ignore-all lint/plugin/no-physical-direction-utility: pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-physical-direction-utilitygrit
-import type { ValidationAuditResponse, ValidationDocResult } from '@inkeep/open-knowledge-core';
+import type {
+ FrontmatterScope,
+ ValidationAuditResponse,
+ ValidationDocResult,
+} from '@inkeep/open-knowledge-core';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import {
AlertCircle,
@@ -66,13 +70,21 @@ export interface LintNavDetail {
/** 1-based column. */
column: number;
/**
- * Producing plugin id. WYSIWYG needs it to decline navigation for
- * diagnostics that have no body anchor: a `frontmatter` violation reports on
- * the region's opening fence, which on a doc with no frontmatter is line 1 —
- * following it would select the first body block, which is not the problem.
- * Source mode anchors by line and consumes every source alike.
+ * Producing plugin id — the diagnostic's identity, carried for consumers
+ * that group or label by producer. Source mode anchors by line and consumes
+ * every source alike.
*/
source?: string;
+ /**
+ * The diagnostic's frontmatter scope, when it has one. WYSIWYG declines
+ * navigation on it: a frontmatter violation has no body anchor — it reports
+ * on the region's opening fence, which on a doc with no frontmatter is
+ * line 1, so following it would select the first body block, which is not
+ * the problem. Scope, not `source`, is the discriminator: a plugin that
+ * validates frontmatter also emits body findings, which carry no scope and
+ * must still navigate.
+ */
+ frontmatterScope?: FrontmatterScope;
}
export const LINT_NAV_EVENT = 'open-knowledge:lint-nav';
@@ -99,6 +111,9 @@ function lintNavDetailOf(docName: string, diagnostic: DiagnosticLike): LintNavDe
line: diagnostic.range.start.line + 1,
column: diagnostic.range.start.character + 1,
source: diagnostic.source,
+ ...(diagnostic.frontmatterScope === undefined
+ ? {}
+ : { frontmatterScope: diagnostic.frontmatterScope }),
};
}
diff --git a/packages/app/src/components/PropertyPanel.tsx b/packages/app/src/components/PropertyPanel.tsx
index 2d5d5f551..7fe265197 100644
--- a/packages/app/src/components/PropertyPanel.tsx
+++ b/packages/app/src/components/PropertyPanel.tsx
@@ -353,22 +353,21 @@ export function PropertyPanel({ provider, reservedKeys, identitySlot }: Property
* reaches the file once the user supplies a value and commits it, so an
* empty placeholder can never land in the doc and quietly satisfy the
* `required` check that produced the row.
+ *
+ * One row per property comes from `partitionFrontmatterProblems`, which is
+ * also what the toolbar counts — a second dedupe here would let the two
+ * drift.
*/
function stageMissingDrafts(): StagedDraft[] {
const staged: StagedDraft[] = [];
- const seen = new Set<string>();
for (const diagnostic of missingProperties) {
const name = diagnostic.frontmatterProperty;
if (name === undefined || name === '') continue;
- // Two schemas can each require the same property, and the diagnostics
- // are per schema.
- if (seen.has(name)) continue;
// The doc may have gained the property since the count was rendered.
if (Object.hasOwn(map, name)) continue;
// A reserved key is not this panel's to add — a skill's `name` is its
// folder identity, renamed by moving the folder, not patched.
if (reserved.has(name)) continue;
- seen.add(name);
const id = `staged-${name}`;
// Re-requesting an add while a row for this property is already open
// keeps that row — rebuilding it would throw away a value the user had
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.okf.test.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.okf.test.ts
new file mode 100644
index 000000000..173d71c05
--- /dev/null
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.okf.test.ts
@@ -0,0 +1,200 @@
+// @vitest-environment jsdom
+/**
+ * OKF frontmatter diagnostics through the WYSIWYG anchoring seams — the block
+ * decoration mapping and the Problems-row navigation. The sibling test file
+ * covers both seams for the built-in `frontmatter` plugin; the OKF plugin is a
+ * second producer of frontmatter diagnostics, and they are anchorless for the
+ * same reason: the validator anchors a missing-`required` violation to the
+ * region's opening fence, which on a doc with NO frontmatter is line 1 — the
+ * first line of body text. Anchoring by line would squiggle (and navigate to) a
+ * correct first block on exactly the docs where the schema error matters most.
+ *
+ * OKF body rules carry no frontmatter scope and must keep their body anchor —
+ * the discriminator is the diagnostic's scope metadata, not the producing
+ * plugin id.
+ *
+ * Diagnostics come from the REAL `lintDocument` pass over the REAL OKF
+ * registry, not hand-built stand-ins, so the tests fail if the producer's
+ * anchoring or metadata changes shape.
+ */
+
+import {
+ sharedExtensions as coreExtensions,
+ DEFAULT_LINTER_CONFIG,
+ type LintDiagnostic,
+ type LinterConfig,
+ lintDocument,
+ MarkdownManager,
+} from '@inkeep/open-knowledge-core';
+import { Editor } from '@tiptap/core';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { LINT_NAV_EVENT, type LintNavDetail } from '@/components/ProblemsPanel';
+import { __resetScrollRestoreCoordination } from '../scroll-restore-coordination.ts';
+import { MarkdownLintDecorations, mapDiagnosticsToBlocks } from './markdown-lint-decorations.ts';
+
+const md = new MarkdownManager({ extensions: coreExtensions });
+
+// A concept-scoped doc name (anything but a reserved `index`/`log` filename).
+const DOC = 'notes/lint-nav-okf';
+
+const okfConfig: LinterConfig = {
+ enabled: true,
+ plugins: {
+ markdownlint: { enabled: false, rules: {} },
+ frontmatter: { enabled: true, schemas: [] },
+ okf: { enabled: true },
+ },
+};
+
+// No frontmatter region at all, so the OKF missing-`type` violation anchors to
+// line 1 — body text. Block 1 carries a wiki-link for the `no-wiki-links` body
+// rule, which MUST keep its anchor.
+// 1: # Heading
+// 2:
+// 3: See [[Wiki Target]] here.
+// 4:
+// 5: Second paragraph.
+const BODY = '# Heading\n\nSee [[Wiki Target]] here.\n\nSecond paragraph.\n';
+
+async function realOkfDiagnostics(): Promise<{
+ frontmatterRequired: LintDiagnostic;
+ noWikiLinks: LintDiagnostic;
+}> {
+ const diagnostics = await lintDocument(BODY, okfConfig, DOC);
+ const frontmatterRequired = diagnostics.find(
+ (d) => d.source === 'okf' && d.code === 'frontmatter-required',
+ );
+ const noWikiLinks = diagnostics.find((d) => d.source === 'okf' && d.code === 'no-wiki-links');
+ if (!frontmatterRequired || !noWikiLinks) {
+ throw new Error('expected the real OKF pass to produce both diagnostics');
+ }
+ return { frontmatterRequired, noWikiLinks };
+}
+
+describe('mapDiagnosticsToBlocks with real OKF diagnostics', () => {
+ test('skips an OKF frontmatter violation on a doc with NO frontmatter region', async () => {
+ const { frontmatterRequired } = await realOkfDiagnostics();
+ // The violation carries frontmatter scope and anchors to body line 1.
+ expect(frontmatterRequired.frontmatterScope).toBe('missing');
+ expect(frontmatterRequired.range.start.line).toBe(0);
+
+ const byBlock = mapDiagnosticsToBlocks(BODY, [frontmatterRequired], md);
+ expect(byBlock.size).toBe(0);
+ });
+
+ test('still maps an OKF body-rule violation to its block', async () => {
+ const { noWikiLinks } = await realOkfDiagnostics();
+ const byBlock = mapDiagnosticsToBlocks(BODY, [noWikiLinks], md);
+ // Line 3 is block 1 (the paragraph carrying the wiki-link).
+ expect([...byBlock.keys()]).toEqual([1]);
+ });
+
+ test('drops only the frontmatter-scoped diagnostic from a mixed OKF set', async () => {
+ const { frontmatterRequired, noWikiLinks } = await realOkfDiagnostics();
+ const byBlock = mapDiagnosticsToBlocks(BODY, [frontmatterRequired, noWikiLinks], md);
+ expect([...byBlock.keys()]).toEqual([1]);
+ expect(byBlock.get(1)).toHaveLength(1);
+ expect(byBlock.get(1)?.[0]?.code).toBe('no-wiki-links');
+ });
+});
+
+describe('Problems-row navigation for OKF diagnostics', () => {
+ let editor: Editor | null = null;
+ let host: HTMLElement | null = null;
+ let scrollIntoView: ReturnType<typeof vi.fn>;
+ let originalScrollIntoView: PropertyDescriptor | undefined;
+ let originalFetch: typeof globalThis.fetch;
+
+ function mountEditor(): Editor {
+ host = document.createElement('div');
+ document.body.appendChild(host);
+ const mounted = new Editor({
+ element: host,
+ extensions: [
+ ...coreExtensions,
+ MarkdownLintDecorations.configure({ docName: DOC, getSource: () => BODY }),
+ ],
+ content: md.parse(BODY),
+ });
+ // jsdom has no layout: `offsetParent` is the plugin's "am I the visible
+ // editor" gate, installed manually like the sibling suite does.
+ Object.defineProperty(mounted.view.dom, 'offsetParent', { value: host, configurable: true });
+ return mounted;
+ }
+
+ /** Dispatch the row-click event with the detail the Problems panel derives from `diagnostic`. */
+ function clickProblemsRow(diagnostic: LintDiagnostic): void {
+ const detail: LintNavDetail & Pick<LintDiagnostic, 'frontmatterScope' | 'frontmatterProperty'> =
+ {
+ docName: DOC,
+ line: diagnostic.range.start.line + 1,
+ column: diagnostic.range.start.character + 1,
+ source: diagnostic.source,
+ ...(diagnostic.frontmatterScope === undefined
+ ? {}
+ : { frontmatterScope: diagnostic.frontmatterScope }),
+ ...(diagnostic.frontmatterProperty === undefined
+ ? {}
+ : { frontmatterProperty: diagnostic.frontmatterProperty }),
+ };
+ window.dispatchEvent(new CustomEvent<LintNavDetail>(LINT_NAV_EVENT, { detail }));
+ }
+
+ beforeEach(() => {
+ __resetScrollRestoreCoordination();
+ originalFetch = globalThis.fetch;
+ globalThis.fetch = vi.fn(async () =>
+ Response.json({ effective: DEFAULT_LINTER_CONFIG }),
+ ) as unknown as typeof fetch;
+ scrollIntoView = vi.fn();
+ originalScrollIntoView = Object.getOwnPropertyDescriptor(
+ HTMLElement.prototype,
+ 'scrollIntoView',
+ );
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ value: scrollIntoView,
+ configurable: true,
+ writable: true,
+ });
+ editor = mountEditor();
+ });
+
+ afterEach(() => {
+ editor?.destroy();
+ editor = null;
+ host?.remove();
+ host = null;
+ if (originalScrollIntoView) {
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', originalScrollIntoView);
+ } else {
+ Reflect.deleteProperty(HTMLElement.prototype, 'scrollIntoView');
+ }
+ globalThis.fetch = originalFetch;
+ __resetScrollRestoreCoordination();
+ });
+
+ test('declines an OKF frontmatter row rather than selecting the first body block', async () => {
+ // The missing-`type` violation reports on line 1, which with no
+ // frontmatter region is the heading — nothing is wrong with it; the
+ // property panel owns this error.
+ const { frontmatterRequired } = await realOkfDiagnostics();
+ const before = editor?.state.selection.from;
+
+ clickProblemsRow(frontmatterRequired);
+
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ expect(editor?.state.selection.from).toBe(before);
+ });
+
+ test('still navigates for an OKF body-rule row', async () => {
+ const { noWikiLinks } = await realOkfDiagnostics();
+
+ clickProblemsRow(noWikiLinks);
+
+ expect(scrollIntoView).toHaveBeenCalledTimes(1);
+ // The wiki-link renders as its own inline node, so the paragraph's
+ // textContent carries only the surrounding prose.
+ const { $from } = editor?.state.selection ?? {};
+ expect($from?.parent.textContent).toContain('See');
+ });
+});
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
index 8ffc4354d..d0b7abbf3 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.test.ts
@@ -127,11 +127,14 @@ describe('mapDiagnosticsToBlocks', () => {
expect(byBlock.size).toBe(0);
});
+ // Mirrors the validator's real output shape: it stamps `frontmatterScope` on
+ // every diagnostic it emits, and that scope is what marks one anchorless.
const fmDiag = (line: number, over: Partial<LintDiagnostic> = {}): LintDiagnostic =>
diag(line, {
source: 'frontmatter',
code: 'required',
message: 'Frontmatter property "status" is required',
+ frontmatterScope: 'missing',
...over,
});
@@ -146,22 +149,26 @@ describe('mapDiagnosticsToBlocks', () => {
});
test('skips a frontmatter violation anchored to a key line inside the region', () => {
- const byBlock = mapDiagnosticsToBlocks(fmSource, [fmDiag(2, { code: 'enum' })], md);
+ const byBlock = mapDiagnosticsToBlocks(
+ fmSource,
+ [fmDiag(2, { code: 'enum', frontmatterScope: 'invalid' })],
+ md,
+ );
expect(byBlock.size).toBe(0);
});
test('skips a frontmatter violation anchored PAST the frontmatter region', () => {
// The one case that separates the two guards: `fmSource` has a 3-line
// region, so line 4 is body. The line-range guard would let this through;
- // only the producing-plugin check catches it. Without this, narrowing
+ // only the scope-metadata check catches it. Without this, narrowing
// `isFrontmatterAnchorless` back to a line check passes the whole suite.
const byBlock = mapDiagnosticsToBlocks(fmSource, [fmDiag(4)], md);
expect(byBlock.size).toBe(0);
});
test('still marks a markdownlint violation on body line 1 of a doc with no frontmatter', () => {
- // The frontmatter skip is by producing plugin, not by position — a
- // body-anchored rule on the same line must keep its decoration.
+ // The frontmatter skip is by scope metadata, not by position — a
+ // scope-less body rule on the same line must keep its decoration.
const byBlock = mapDiagnosticsToBlocks(body, [diag(1)], md);
expect(byBlock.has(0)).toBe(true);
});
@@ -311,8 +318,11 @@ describe('Problems-row navigation — scroll suppression', () => {
return mounted;
}
- function clickProblemsRow(line: number, source?: string): void {
- const detail: LintNavDetail = { docName: DOC, line, column: 1, source };
+ function clickProblemsRow(
+ line: number,
+ over: Pick<LintNavDetail, 'source' | 'frontmatterScope'> = {},
+ ): void {
+ const detail: LintNavDetail = { docName: DOC, line, column: 1, ...over };
window.dispatchEvent(new CustomEvent<LintNavDetail>(LINT_NAV_EVENT, { detail }));
}
@@ -363,7 +373,22 @@ describe('Problems-row navigation — scroll suppression', () => {
// block that has nothing wrong with it; the property panel owns that error.
const before = editor?.state.selection.from;
- clickProblemsRow(1, 'frontmatter');
+ // The detail the panel derives from a real frontmatter violation carries
+ // the scope the validator stamped.
+ clickProblemsRow(1, { source: 'frontmatter', frontmatterScope: 'missing' });
+
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ expect(editor?.state.selection.from).toBe(before);
+ });
+
+ test('declines an invalid-frontmatter row on the same scope-not-producer basis', () => {
+ // 'invalid' is the other scope the validator stamps. The decline keys on
+ // the scope being present at all, not on which scope it is — narrowing it
+ // to 'missing' would send this row to whatever body block line 1 resolves
+ // to on a doc that has no frontmatter region.
+ const before = editor?.state.selection.from;
+
+ clickProblemsRow(1, { source: 'frontmatter', frontmatterScope: 'invalid' });
expect(scrollIntoView).not.toHaveBeenCalled();
expect(editor?.state.selection.from).toBe(before);
diff --git a/packages/app/src/editor/extensions/markdown-lint-decorations.ts b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
index f4df1460b..49cb3b805 100644
--- a/packages/app/src/editor/extensions/markdown-lint-decorations.ts
+++ b/packages/app/src/editor/extensions/markdown-lint-decorations.ts
@@ -33,6 +33,7 @@
import { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom';
import {
sharedExtensions as coreExtensions,
+ isFrontmatterScoped,
type LintDiagnostic,
type LinterConfig,
type LintTextEdit,
@@ -73,17 +74,20 @@ const RECOMPUTE_DEBOUNCE_MS = 400;
* no body anchor are skipped — they stay visible in the Problems panel.
*
* Two kinds have no anchor. Anything reported INSIDE the frontmatter region
- * belongs to the property panel, not the body. And every `frontmatter`-source
- * diagnostic is anchorless regardless of where its line lands: the validator
- * anchors a missing-`required` violation to the region's opening fence, which
- * on a doc with NO frontmatter at all is line 1 — the first line of body text.
- * Line-based skipping alone therefore paints a squiggle on the one construct
- * that is definitionally not the problem (there is nothing there to be wrong),
- * on the docs where the error matters most. `isFrontmatterAnchorless` keys off
- * the producing plugin instead, which holds for both cases.
+ * belongs to the property panel, not the body. And every diagnostic produced
+ * by the frontmatter validator is anchorless regardless of where its line
+ * lands: the validator anchors a missing-`required` violation to the region's
+ * opening fence, which on a doc with NO frontmatter at all is line 1 — the
+ * first line of body text. Line-based skipping alone therefore paints a
+ * squiggle on the one construct that is definitionally not the problem (there
+ * is nothing there to be wrong), on the docs where the error matters most.
+ * `isFrontmatterAnchorless` keys off the scope metadata the validator stamps
+ * instead — which identifies its diagnostics plugin-agnostically (more than
+ * one plugin validates frontmatter, and those plugins' body rules must keep
+ * their anchors) — and holds for both cases.
*/
function isFrontmatterAnchorless(diagnostic: LintDiagnostic): boolean {
- return diagnostic.source === 'frontmatter';
+ return isFrontmatterScoped(diagnostic);
}
export function mapDiagnosticsToBlocks(
@@ -587,10 +591,11 @@ export const MarkdownLintDecorations = Extension.create<MarkdownLintDecorationsO
if (!view.dom.isConnected || view.dom.offsetParent === null) return false;
// Frontmatter diagnostics have no WYSIWYG anchor (property panel
// owns that region) — leave the banked source-mode intent alive.
- // Checked by producing plugin, not by line, for the same reason the
+ // Checked by scope metadata, not by line, for the same reason the
// decoration mapping does: on a doc with no frontmatter the
- // violation's line points into the body.
- if (detail.source === 'frontmatter') return false;
+ // violation's line points into the body. And not by producing
+ // plugin: the same plugins emit body findings that must navigate.
+ if (isFrontmatterScoped(detail)) return false;
const source = getSource?.() ?? md.serialize(view.state.doc.toJSON());
const { spans, fmLineCount } = computeSourceBlockSpans(source, md);
if (spans.length !== comparableChildCount(view.state.doc)) return false;
diff --git a/packages/app/src/editor/useFrontmatterDiagnostics.okf.dom.test.tsx b/packages/app/src/editor/useFrontmatterDiagnostics.okf.dom.test.tsx
new file mode 100644
index 000000000..a6966c599
--- /dev/null
+++ b/packages/app/src/editor/useFrontmatterDiagnostics.okf.dom.test.tsx
@@ -0,0 +1,126 @@
+/**
+ * The badge hook's lint pass must produce the OKF plugin's frontmatter
+ * diagnostics — the sibling dom test only exercises the built-in frontmatter
+ * plugin, so a badge pass that silently disables the OKF producer stays green
+ * there while the Add-properties badge never shows for an OKF-governed doc.
+ *
+ * Real hook, real Y.Doc, real `lintDocument` over the real OKF registry: the
+ * exact composition `EditorArea` / `PropertyPanel` run
+ * (`partitionFrontmatterProblems(useFrontmatterDiagnostics(provider, config))`).
+ */
+
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import type { LinterConfig } from '@inkeep/open-knowledge-core';
+import { cleanup, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
+import * as Y from 'yjs';
+import {
+ partitionFrontmatterProblems,
+ useFrontmatterDiagnostics,
+} from './useFrontmatterDiagnostics';
+
+// A concept-scoped doc name (anything but a reserved `index`/`log` filename).
+const DOC_NAME = 'usability-sessions/kenny/notes/serafin';
+
+function fakeProvider(initial: string): { provider: HocuspocusProvider; doc: Y.Doc } {
+ const doc = new Y.Doc();
+ doc.getText('source').insert(0, initial);
+ return {
+ provider: {
+ document: doc,
+ configuration: { name: DOC_NAME },
+ } as unknown as HocuspocusProvider,
+ doc,
+ };
+}
+
+// OKF enabled; the frontmatter plugin on with no authored schemas (the shape a
+// project has right after enabling OKF); markdownlint deliberately ENABLED so
+// the suppression assertions below prove body findings still never reach this
+// frontmatter-only surface.
+const okfEnabled: LinterConfig = {
+ enabled: true,
+ plugins: {
+ markdownlint: { enabled: true, rules: {} },
+ frontmatter: { enabled: true, schemas: [] },
+ okf: { enabled: true },
+ },
+};
+
+const frontmatterPluginOff: LinterConfig = {
+ ...okfEnabled,
+ plugins: {
+ ...okfEnabled.plugins,
+ frontmatter: { enabled: false, schemas: [] },
+ },
+};
+
+// Frontmatter without the OKF-required `type`; a body wiki-link (OKF body rule
+// `no-wiki-links`) and a hard tab (markdownlint MD010) that must stay off the
+// badge surface even once the OKF producer participates in the pass.
+const MISSING_TYPE = '---\ntitle: Serafin\ntags: []\n---\n\nSee [[Wiki Target]]\there.\n';
+
+afterEach(() => cleanup());
+
+describe('useFrontmatterDiagnostics with the OKF plugin enabled', () => {
+ test('reports the OKF missing-`type` violation with full badge metadata', async () => {
+ const { provider } = fakeProvider(MISSING_TYPE);
+ const { result } = renderHook(() => useFrontmatterDiagnostics(provider, okfEnabled));
+
+ await waitFor(() =>
+ expect(
+ result.current.some(
+ (d) =>
+ d.source === 'okf' &&
+ d.code === 'frontmatter-required' &&
+ d.frontmatterScope === 'missing' &&
+ d.frontmatterProperty === 'type',
+ ),
+ ).toBe(true),
+ );
+ // Frontmatter-only surface: scope-less findings (the body wiki-link, the
+ // markdownlint hard tab) must not ride along.
+ expect(result.current.every((d) => d.frontmatterScope !== undefined)).toBe(true);
+ });
+
+ test('feeds the Add-properties badge through partitionFrontmatterProblems', async () => {
+ const { provider } = fakeProvider(MISSING_TYPE);
+ const { result } = renderHook(() => useFrontmatterDiagnostics(provider, okfEnabled));
+
+ await waitFor(() => {
+ const { missing, invalid } = partitionFrontmatterProblems(result.current);
+ expect(missing.map((d) => d.frontmatterProperty)).toEqual(['type']);
+ expect(invalid).toHaveLength(0);
+ });
+ });
+
+ test('reports the OKF violation with the frontmatter plugin itself disabled', async () => {
+ // Enabling OKF deliberately does not require enabling the frontmatter
+ // plugin (its schemas ship inside the plugin, no files on disk), so the
+ // badge must work for a project running OKF alone.
+ const { provider } = fakeProvider(MISSING_TYPE);
+ const { result } = renderHook(() => useFrontmatterDiagnostics(provider, frontmatterPluginOff));
+
+ await waitFor(() =>
+ expect(
+ result.current.some((d) => d.source === 'okf' && d.frontmatterScope === 'missing'),
+ ).toBe(true),
+ );
+ });
+
+ test('clears once the missing `type` is added', async () => {
+ // The full badge loop: violation reported live, then satisfied by an edit.
+ // Ends at [] only after the diagnostic was observed, so a hook that never
+ // reports cannot pass by staying empty throughout.
+ const { provider, doc } = fakeProvider('---\ntitle: Serafin\n---\n\nPlain notes.\n');
+ const { result } = renderHook(() => useFrontmatterDiagnostics(provider, okfEnabled));
+ await waitFor(() =>
+ expect(result.current.some((d) => d.frontmatterProperty === 'type')).toBe(true),
+ );
+
+ const ytext = doc.getText('source');
+ ytext.delete(0, ytext.length);
+ ytext.insert(0, '---\ntitle: Serafin\ntype: Note\n---\n\nPlain notes.\n');
+ await waitFor(() => expect(result.current).toEqual([]));
+ });
+});
diff --git a/packages/app/src/editor/useFrontmatterDiagnostics.okf.test.ts b/packages/app/src/editor/useFrontmatterDiagnostics.okf.test.ts
new file mode 100644
index 000000000..b15222851
--- /dev/null
+++ b/packages/app/src/editor/useFrontmatterDiagnostics.okf.test.ts
@@ -0,0 +1,164 @@
+/**
+ * The badge partition composed with the REAL lint engine over the REAL OKF
+ * registry — the sibling unit test feeds `partitionFrontmatterProblems` only
+ * hand-built diagnostics, so it cannot notice when a real producer's output is
+ * dropped wholesale.
+ *
+ * The contract under test: a diagnostic carrying `frontmatterScope` reports on
+ * the frontmatter affordances regardless of producing plugin (`missing` → the
+ * Add-properties button, `invalid` → the property panel's count), while a
+ * scope-less diagnostic — an OKF body rule, a markdownlint finding — belongs to
+ * neither bucket. Plugin identity is not a proxy for frontmatter-ness: the OKF
+ * plugin produces both kinds.
+ */
+
+import { type LinterConfig, lintDocument } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import { partitionFrontmatterProblems } from './useFrontmatterDiagnostics.ts';
+
+// A concept-scoped doc name (anything but a reserved `index`/`log` filename).
+const DOC_NAME = 'usability-sessions/kenny/notes/serafin';
+
+// OKF on; the frontmatter plugin on with no authored schemas (the shape a
+// project has right after enabling OKF); markdownlint on so its scope-less
+// findings are available to the exclusion tests below.
+const config: LinterConfig = {
+ enabled: true,
+ plugins: {
+ markdownlint: { enabled: true, rules: {} },
+ frontmatter: { enabled: true, schemas: [] },
+ okf: { enabled: true },
+ },
+};
+
+// The sentence both a `type: array` OKF recommendation and a `type: array`
+// project schema produce for a scalar `tags` — the two are indistinguishable to
+// a reader, which is what makes the second one a restatement.
+const TAGS_MUST_BE_ARRAY = 'Frontmatter property "tags" must be array';
+
+describe('partitionFrontmatterProblems over real OKF diagnostics', () => {
+ test('routes an OKF missing-required diagnostic to `missing`', async () => {
+ const text = '---\ntitle: Serafin\ndescription: Session notes\ntags: []\n---\n\nSome notes.\n';
+ const diagnostics = await lintDocument(text, config, DOC_NAME);
+
+ // Producer half of the contract (already upheld): the OKF plugin emits the
+ // violation with full badge metadata.
+ const produced = diagnostics.find(
+ (d) => d.source === 'okf' && d.code === 'frontmatter-required',
+ );
+ expect(produced?.frontmatterScope).toBe('missing');
+ expect(produced?.frontmatterProperty).toBe('type');
+
+ // Consumer half: the Add-properties badge must count it.
+ const { missing, invalid } = partitionFrontmatterProblems(diagnostics);
+ expect(missing.map((d) => d.frontmatterProperty)).toEqual(['type']);
+ expect(invalid).toHaveLength(0);
+ });
+
+ test('routes an OKF invalid-scope diagnostic to `invalid`', async () => {
+ // `type` present (conformance floor met); `tags` authored as a string where
+ // the OKF recommended schema pins an array — a present-but-wrong property.
+ const text = '---\ntype: Note\ntags: not-a-list\n---\n\nSome notes.\n';
+ const diagnostics = await lintDocument(text, config, DOC_NAME);
+
+ const produced = diagnostics.find(
+ (d) => d.source === 'okf' && d.frontmatterScope === 'invalid',
+ );
+ expect(produced?.message).toContain('tags');
+
+ const { missing, invalid } = partitionFrontmatterProblems(diagnostics);
+ expect(missing).toHaveLength(0);
+ expect(invalid.some((d) => d.source === 'okf' && d.message.includes('tags'))).toBe(true);
+ });
+
+ test('two producers requiring `type` count as one property to add', async () => {
+ // The shape a project takes on when it adopts OKF over an existing
+ // `contentRules.frontmatter` schema: both require `type` and both report it,
+ // so a per-diagnostic count would put 2 on the Add-properties badge and list
+ // the same add twice in its tooltip, while clicking stages one row.
+ const alsoRequiresType: LinterConfig = {
+ ...config,
+ plugins: {
+ ...config.plugins,
+ frontmatter: {
+ enabled: true,
+ schemas: [
+ {
+ appliesTo: '**',
+ file: 'notes.json',
+ schema: {
+ type: 'object',
+ required: ['type'],
+ properties: { type: { type: 'string' } },
+ },
+ },
+ ],
+ },
+ },
+ };
+ const text = '---\ntitle: Serafin\n---\n\nSome notes.\n';
+ const diagnostics = await lintDocument(text, alsoRequiresType, DOC_NAME);
+
+ // Both producers really do report it — otherwise the dedupe below is vacuous.
+ const producers = diagnostics
+ .filter((d) => d.frontmatterScope === 'missing' && d.frontmatterProperty === 'type')
+ .map((d) => d.source);
+ expect(new Set(producers)).toEqual(new Set(['okf', 'frontmatter']));
+
+ const { missing } = partitionFrontmatterProblems(diagnostics);
+ expect(missing.map((d) => d.frontmatterProperty)).toEqual(['type']);
+ });
+
+ test('two producers stating one `tags` fault count as one problem', async () => {
+ // The `invalid` counterpart of the dedupe above, and the same adoption
+ // shape: OKF's recommended schema pins `tags` as an array, and a project
+ // schema that pins it the same way makes both state one sentence about one
+ // existing row. The property panel counts and lists those sentences.
+ const alsoPinsTags: LinterConfig = {
+ ...config,
+ plugins: {
+ ...config.plugins,
+ frontmatter: {
+ enabled: true,
+ schemas: [
+ {
+ appliesTo: '**',
+ file: 'notes.json',
+ schema: {
+ type: 'object',
+ properties: { tags: { type: 'array', items: { type: 'string' } } },
+ },
+ },
+ ],
+ },
+ },
+ };
+ const text = '---\ntype: Note\ntags: not-a-list\n---\n\nSome notes.\n';
+ const diagnostics = await lintDocument(text, alsoPinsTags, DOC_NAME);
+
+ // Both producers really do state it, verbatim — otherwise the collapse below
+ // is vacuous.
+ const tagsFault = diagnostics.filter(
+ (d) => d.frontmatterScope === 'invalid' && d.message === TAGS_MUST_BE_ARRAY,
+ );
+ expect(new Set(tagsFault.map((d) => d.source))).toEqual(new Set(['okf', 'frontmatter']));
+
+ const { invalid } = partitionFrontmatterProblems(diagnostics);
+ expect(invalid.filter((d) => d.message === TAGS_MUST_BE_ARRAY)).toHaveLength(1);
+ });
+
+ test('excludes scope-less diagnostics (OKF body rules, markdownlint) from both buckets', async () => {
+ // Conformant frontmatter; the body trips the OKF `no-wiki-links` body rule
+ // and markdownlint's hard-tab rule. Neither carries `frontmatterScope`, so
+ // neither belongs on a frontmatter affordance.
+ const text = '---\ntype: Note\n---\n\nSee [[Wiki Target]]\there.\n';
+ const diagnostics = await lintDocument(text, config, DOC_NAME);
+
+ expect(diagnostics.some((d) => d.source === 'okf' && d.code === 'no-wiki-links')).toBe(true);
+ expect(diagnostics.every((d) => d.code !== 'frontmatter-required')).toBe(true);
+
+ const { missing, invalid } = partitionFrontmatterProblems(diagnostics);
+ expect(missing).toHaveLength(0);
+ expect(invalid).toHaveLength(0);
+ });
+});
diff --git a/packages/app/src/editor/useFrontmatterDiagnostics.test.ts b/packages/app/src/editor/useFrontmatterDiagnostics.test.ts
index 864012612..293c54eff 100644
--- a/packages/app/src/editor/useFrontmatterDiagnostics.test.ts
+++ b/packages/app/src/editor/useFrontmatterDiagnostics.test.ts
@@ -60,19 +60,22 @@ describe('partitionFrontmatterProblems', () => {
expect(invalid.map((d) => d.message)).toEqual(['b']);
});
- test('a diagnostic with no scope falls to invalid', () => {
- // Predates the field. Invalid keeps it on the panel rather than inviting an
- // add for a property that may already exist.
+ test('a diagnostic with no scope is excluded from both buckets', () => {
+ // No live producer emits a frontmatter diagnostic without scope — the
+ // validator stamps `frontmatterScope` unconditionally — so a scope-less
+ // diagnostic is a body finding, whatever its source. Routing it to either
+ // bucket would inflate a frontmatter count with a problem neither
+ // affordance can act on.
const { missing, invalid } = partitionFrontmatterProblems([diag({})]);
expect(missing).toHaveLength(0);
- expect(invalid).toHaveLength(1);
+ expect(invalid).toHaveLength(0);
});
test('a non-frontmatter diagnostic is excluded from both buckets', () => {
- // A markdownlint (or any future third-plugin) diagnostic carries no
- // frontmatterScope; without a source guard it would fall to `invalid` and
- // inflate the "N do not match the schema" count. The badge is a frontmatter
- // count, so non-frontmatter sources belong in neither bucket.
+ // A markdownlint (or any future third-plugin) body diagnostic carries no
+ // frontmatterScope; if presence weren't the discriminator it would fall to
+ // `invalid` and inflate the "N do not match the schema" count. The badge is
+ // a frontmatter count, so scope-less findings belong in neither bucket.
const { missing, invalid } = partitionFrontmatterProblems([
diag({ source: 'markdownlint', code: 'MD010', message: 'Hard tabs' }),
]);
@@ -80,6 +83,70 @@ describe('partitionFrontmatterProblems', () => {
expect(invalid).toHaveLength(0);
});
+ test('two schemas requiring one property yield one missing entry', () => {
+ // Every consumer of `missing` counts rows to add — the badge, the tooltip
+ // that promises what a click will add, the panel that stages them — so a
+ // per-diagnostic count would advertise two adds and perform one.
+ const { missing } = partitionFrontmatterProblems([
+ diag({ frontmatterScope: 'missing', frontmatterProperty: 'type', message: 'schema A' }),
+ diag({ frontmatterScope: 'missing', frontmatterProperty: 'type', message: 'schema B' }),
+ ]);
+ // The first survives, so the tooltip still has a message to show.
+ expect(missing.map((d) => d.message)).toEqual(['schema A']);
+ });
+
+ test('distinct missing properties are each kept', () => {
+ const { missing } = partitionFrontmatterProblems([
+ diag({ frontmatterScope: 'missing', frontmatterProperty: 'type' }),
+ diag({ frontmatterScope: 'missing', frontmatterProperty: 'status' }),
+ ]);
+ expect(missing.map((d) => d.frontmatterProperty)).toEqual(['type', 'status']);
+ });
+
+ test('invalid is not deduped by property', () => {
+ // Two schemas can fault one EXISTING row for different reasons, and the row
+ // is already there to carry both — collapsing them would hide one.
+ const { invalid } = partitionFrontmatterProblems([
+ diag({ frontmatterScope: 'invalid', frontmatterProperty: 'tags', message: 'must be array' }),
+ diag({ frontmatterScope: 'invalid', frontmatterProperty: 'tags', message: 'too short' }),
+ ]);
+ expect(invalid.map((d) => d.message)).toEqual(['must be array', 'too short']);
+ });
+
+ test('two schemas stating one fault yield one invalid entry', () => {
+ // The `invalid` counterpart: when two schemas pin one property the same way
+ // they restate the identical sentence, and this bucket's consumers count and
+ // list sentences — so a per-diagnostic count would read 2 and show one
+ // problem twice. Only the restatement collapses; the test above keeps two
+ // different faults on one row apart.
+ const { invalid } = partitionFrontmatterProblems([
+ diag({
+ frontmatterScope: 'invalid',
+ source: 'okf',
+ code: 'frontmatter-recommended',
+ message: 'Frontmatter property "tags" must be array',
+ }),
+ diag({
+ frontmatterScope: 'invalid',
+ source: 'frontmatter',
+ code: 'type',
+ message: 'Frontmatter property "tags" must be array',
+ }),
+ ]);
+ // The first survives, so the sentence the panel shows is unchanged.
+ expect(invalid.map((d) => d.code)).toEqual(['frontmatter-recommended']);
+ });
+
+ test('unnamed missing findings are not collapsed into one', () => {
+ // Nothing names a property to collapse on, so folding them together would
+ // drop a distinct problem rather than a duplicate one.
+ const { missing } = partitionFrontmatterProblems([
+ diag({ frontmatterScope: 'missing', message: 'a' }),
+ diag({ frontmatterScope: 'missing', message: 'b' }),
+ ]);
+ expect(missing.map((d) => d.message)).toEqual(['a', 'b']);
+ });
+
test('an empty set yields two empty buckets', () => {
const { missing, invalid } = partitionFrontmatterProblems([]);
expect(missing).toEqual([]);
diff --git a/packages/app/src/editor/useFrontmatterDiagnostics.ts b/packages/app/src/editor/useFrontmatterDiagnostics.ts
index cc6b3f5b6..4abf2539f 100644
--- a/packages/app/src/editor/useFrontmatterDiagnostics.ts
+++ b/packages/app/src/editor/useFrontmatterDiagnostics.ts
@@ -3,27 +3,40 @@
* badge's data source.
*
* Frontmatter violations have no body anchor (the WYSIWYG decoration pass
- * skips them by producing plugin), so the editor needs a surface of its own to
+ * skips them by scope metadata), so the editor needs a surface of its own to
* report them: the badge on the Add-properties button. This hook feeds it.
*
* It runs the SAME `lintDocument` entry point the Problems panel does, with
- * every other plugin forced off, rather than reaching for the frontmatter
- * validator directly. Going through the public seam is what keeps the badge
- * count and the panel's frontmatter rows from ever disagreeing — a
- * hand-rolled second call path would drift the moment plugin dispatch,
- * `appliesTo` matching, or schema selection changed on one side only.
+ * every plugin that produces no frontmatter diagnostics forced off, rather
+ * than reaching for the frontmatter validator directly. Going through the
+ * public seam is what keeps the badge count and the panel's frontmatter rows
+ * from ever disagreeing — a hand-rolled second call path would drift the
+ * moment plugin dispatch, `appliesTo` matching, or schema selection changed on
+ * one side only.
*
* A second pass rather than a shared one: the toolbar and the doc panel are
* siblings with no data channel between them, and the panel's diagnostics come
* bundled with link findings and validation-store bookkeeping that the toolbar
- * has no use for. Disabling the other plugins reduces this pass to a single
- * synchronous ajv validation over the frontmatter object, which is cheap
- * enough that a second pass costs less than lifting the panel's state — but it
- * is the same `useDocDiagnostics` effect, not a copy of it.
+ * has no use for. It is also the same `useDocDiagnostics` effect, not a copy of
+ * it, so it costs less than lifting the panel's state.
+ *
+ * What keeps that second pass cheap is `selectFrontmatterOnlyConfig`: each
+ * producer's slice arrives narrowed to its frontmatter half, so a producer that
+ * also carries body rules turns them off before they parse anything. Filtering
+ * the output instead would still pay for a full document parse per debounce
+ * tick on a per-visible-doc render path, for findings this surface discards —
+ * and the panel is not there to have already paid it, since the common case is
+ * the Problems panel closed.
*/
import type { HocuspocusProvider } from '@hocuspocus/provider';
-import { LINT_PLUGINS, type LintDiagnostic, type LinterConfig } from '@inkeep/open-knowledge-core';
+import {
+ isFrontmatterScoped,
+ LINT_PLUGINS,
+ type LintDiagnostic,
+ type LinterConfig,
+ selectFrontmatterOnlyConfig,
+} from '@inkeep/open-knowledge-core';
import { useDocDiagnostics } from './useDocDiagnostics.ts';
/**
@@ -32,16 +45,34 @@ import { useDocDiagnostics } from './useDocDiagnostics.ts';
* `missing` names a property the document does not have, so there is no row to
* mark — it reports on the Add-properties button. `invalid` is a property that
* exists and is wrong, which the property panel can point at, so it reports on
- * the panel's own count. The validator supplies the distinction
- * (`frontmatterScope`); a diagnostic without it predates the field and is
- * treated as invalid, which keeps it on the panel rather than inviting the user
- * to add something twice.
+ * the panel's own count.
+ *
+ * Only frontmatter-scoped diagnostics count, keyed on the scope metadata the
+ * validator stamps rather than on producing plugin: more than one plugin
+ * produces frontmatter diagnostics, and the same plugins also produce body
+ * findings that carry no scope. Keying on `isFrontmatterScoped` admits every
+ * producer's frontmatter findings and keeps everything else — body rules,
+ * markdownlint, whatever a future plugin emits without scope — off both badge
+ * counts.
+ *
+ * Both buckets collapse duplicates, each on the identity its own consumers
+ * count, because two schemas validating one document can restate one problem.
*
- * Only `frontmatter`-source diagnostics count. `frontmatterOnly` already keeps
- * the hook's pass to that source today, but the registry is append-designed
- * (`LINT_PLUGIN_IDS`): a future plugin would carry no `frontmatterScope` and
- * silently swell the `invalid` count. Guarding on source here means the two
- * badge counts stay frontmatter-only regardless of what else the pass produces.
+ * `missing` carries one entry per PROPERTY: every consumer of it — the badge
+ * count, the tooltip listing what a click will add, the panel that stages the
+ * rows — is counting rows to add, so a per-diagnostic count would advertise two
+ * adds and perform one.
+ *
+ * `invalid` carries one entry per MESSAGE. Those rows already exist, so its
+ * consumers count and list FAULTS, not rows, and the property is the wrong key
+ * there: two schemas can fault one row for genuinely different reasons (wrong
+ * type AND outside an enum) and both belong on the list. The message is the
+ * whole of what that surface shows, so two schemas pinning one property the same
+ * way state the identical sentence twice, and only that restatement collapses.
+ *
+ * The first diagnostic of each identity survives, so every entry still carries a
+ * message. Deduping here rather than at each consumer is what stops a badge
+ * reading 2 from acting on 1.
*/
export function partitionFrontmatterProblems(diagnostics: readonly LintDiagnostic[]): {
missing: LintDiagnostic[];
@@ -49,57 +80,56 @@ export function partitionFrontmatterProblems(diagnostics: readonly LintDiagnosti
} {
const missing: LintDiagnostic[] = [];
const invalid: LintDiagnostic[] = [];
+ const named = new Set<string>();
+ const stated = new Set<string>();
for (const diagnostic of diagnostics) {
- if (diagnostic.source !== 'frontmatter') continue;
- if (diagnostic.frontmatterScope === 'missing') missing.push(diagnostic);
- else invalid.push(diagnostic);
+ if (!isFrontmatterScoped(diagnostic)) continue;
+ if (diagnostic.frontmatterScope !== 'missing') {
+ if (stated.has(diagnostic.message)) continue;
+ stated.add(diagnostic.message);
+ invalid.push(diagnostic);
+ continue;
+ }
+ const property = diagnostic.frontmatterProperty;
+ // An unnamed missing-scope finding has no property to collapse on, so it
+ // stays its own entry rather than folding every unnamed one into one.
+ if (property !== undefined && property !== '') {
+ if (named.has(property)) continue;
+ named.add(property);
+ }
+ missing.push(diagnostic);
}
return { missing, invalid };
}
/**
- * `config` with every plugin but frontmatter disabled. Derived from the config's
- * own plugin map rather than naming markdownlint: the registry is append-designed,
- * so a hardcoded list would silently start running a third plugin's pass here —
- * the same growth `partitionFrontmatterProblems` guards its output against.
- *
- * Rebuilt rather than mutated in place. Assigning through a union-typed key
- * (`plugins[id] = …`) asks for a value assignable to EVERY slice at once, which
- * no single slice satisfies once the registry holds more than one shape — so the
- * in-place form stopped compiling the moment a third plugin landed.
- *
- * Still driven by `LINT_PLUGINS`, not by the config's own keys: a config that
- * predates a plugin has no entry for it, and the registry walk is what puts a
- * disabled one there. Mapping `config.plugins` instead would leave that key
- * absent, and `lintDocument` reads `slice.enabled` off every registered plugin
- * without a presence check.
- */
-function frontmatterOnly(config: LinterConfig): LinterConfig {
- const plugins = Object.fromEntries(
- LINT_PLUGINS.map(({ id }) => [
- id,
- id === 'frontmatter' ? config.plugins[id] : { ...config.plugins[id], enabled: false },
- ]),
- ) as LinterConfig['plugins'];
- return { ...config, plugins };
-}
-
-/**
- * Live `frontmatter`-source diagnostics for `provider`'s doc under `config`.
- * Returns `[]` when either is null, when linting is off, or when the
- * frontmatter plugin is disabled.
+ * Live frontmatter-scoped diagnostics for `provider`'s doc under `config`.
+ * Returns `[]` when either is null, when linting is off, or when no
+ * frontmatter-producing plugin is enabled.
*
* Delegates to `useDocDiagnostics` with a frontmatter-only config rather than
* repeating its effect: the debounce, the config-hash key, the observe/
* unobserve pair, and the cancel-on-teardown guard are all subtleties that
* would have to stay in lockstep across two copies, and a divergence would be
- * silent. Handing it a `null` config when the plugin is off short-circuits
+ * silent. Handing it a `null` config when every producer is off short-circuits
* before the async pass instead of relying on `lintDocument` to return empty.
+ *
+ * The scope filter still runs on the output. Narrowing decides what the pass
+ * COSTS; the filter is what makes the surface's contract independent of it, so
+ * a producer that narrows imperfectly cannot put a body finding on the badge.
*/
export function useFrontmatterDiagnostics(
provider: HocuspocusProvider | null,
config: LinterConfig | null,
): LintDiagnostic[] {
- const active = config?.enabled === true && config.plugins.frontmatter.enabled;
- return useDocDiagnostics(provider, active && config ? frontmatterOnly(config) : null);
+ const active =
+ config?.enabled === true &&
+ LINT_PLUGINS.some(
+ (plugin) => plugin.frontmatter !== undefined && config.plugins[plugin.id]?.enabled === true,
+ );
+ const diagnostics = useDocDiagnostics(
+ provider,
+ active && config ? selectFrontmatterOnlyConfig(config) : null,
+ );
+ return diagnostics.filter(isFrontmatterScoped);
}
diff --git a/packages/app/src/lib/frontmatter-enum-constraints.ts b/packages/app/src/lib/frontmatter-enum-constraints.ts
index 864128192..2d7302613 100644
--- a/packages/app/src/lib/frontmatter-enum-constraints.ts
+++ b/packages/app/src/lib/frontmatter-enum-constraints.ts
@@ -12,11 +12,7 @@
* validate.
*/
-import {
- type LinterConfig,
- selectApplicableFrontmatterSchemas,
- selectOkfFrontmatterSchemas,
-} from '@inkeep/open-knowledge-core';
+import { type LinterConfig, selectGoverningFrontmatterSchemas } from '@inkeep/open-knowledge-core';
export interface FieldEnumConstraint {
values: string[];
@@ -54,20 +50,12 @@ export function enumConstraintsForDoc(
// so the offered values would depend on schema order and could violate a
// schema seen earlier.
const droppedToFreeText = new Set<string>();
- if (!config?.enabled || docName === undefined || docName === '') return constraints;
- // Both schema sources feed the same intersection: the project's authored mappings
- // and, when the OKF plugin is on, its built-in profile. A field governed by both
- // must offer only values satisfying both, which is what the conjunction below
- // already does — so the sources concatenate rather than branching.
- const frontmatterSlice = config.plugins.frontmatter;
- const okfSlice = config.plugins.okf;
- const governing = [
- ...(frontmatterSlice?.enabled
- ? selectApplicableFrontmatterSchemas(frontmatterSlice.schemas, docName)
- : []),
- ...(okfSlice?.enabled ? selectOkfFrontmatterSchemas(okfSlice.rules, docName) : []),
- ];
+ // Every frontmatter-capable plugin's schemas feed the same intersection: a
+ // field governed by more than one producer must offer only values satisfying
+ // all of them, which is what the conjunction below already does — so the
+ // shared selector concatenates the sources rather than branching per plugin.
+ const governing = selectGoverningFrontmatterSchemas(config, docName);
for (const { schema } of governing) {
const properties = isRecord(schema.properties) ? schema.properties : {};
diff --git a/packages/app/src/lib/frontmatter-schema-fields.okf.test.ts b/packages/app/src/lib/frontmatter-schema-fields.okf.test.ts
new file mode 100644
index 000000000..646c245f4
--- /dev/null
+++ b/packages/app/src/lib/frontmatter-schema-fields.okf.test.ts
@@ -0,0 +1,131 @@
+/**
+ * `schemaFieldsForDoc` over the OKF profile's schemas. The OKF plugin is a
+ * second producer of governing frontmatter schemas — the sibling
+ * `enumConstraintsForDoc` already folds `selectOkfFrontmatterSchemas` in, and
+ * the field catalogue owes the add-property picker the same participation: a
+ * staged row for the OKF-required `type` takes its widget type and required
+ * hint from here.
+ *
+ * These exercise the REAL shipped OKF schemas rather than a stand-in, so a
+ * change to the shipped contract fails here.
+ */
+
+import type { LinterConfig, OkfRuleId } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import { schemaFieldsForDoc } from './frontmatter-schema-fields.ts';
+
+function configWithOkf(
+ okf: { enabled: boolean; rules?: Partial<Record<OkfRuleId, boolean>> },
+ frontmatter: {
+ enabled: boolean;
+ schemas: { appliesTo?: string | string[]; file: string; schema?: Record<string, unknown> }[];
+ } = { enabled: false, schemas: [] },
+): LinterConfig {
+ return {
+ enabled: true,
+ plugins: {
+ markdownlint: { enabled: false, rules: {} },
+ frontmatter,
+ okf,
+ },
+ } as LinterConfig;
+}
+
+describe('schemaFieldsForDoc — the OKF profile', () => {
+ test('OKF alone offers its declared fields, with the frontmatter plugin off', () => {
+ // Enabling OKF deliberately does not require enabling the frontmatter
+ // plugin, so the picker must offer the profile's fields for a project
+ // running OKF alone.
+ const fields = schemaFieldsForDoc(configWithOkf({ enabled: true }), 'notes/concept');
+
+ const type = fields.get('type');
+ expect(type?.required).toBe(true);
+ // `type` is declared `type: string` with no date format → text widget.
+ expect(type?.type).toBe('text');
+ // The schema's agent-facing description is the picker's secondary text.
+ expect(type?.description).toBeTruthy();
+
+ // A recommended-family field keeps its declared widget shape too.
+ expect(fields.get('tags')?.type).toBe('list');
+ expect(fields.get('tags')?.required).toBe(false);
+ });
+
+ test('merges OKF fields with a user-authored schema governing the same doc', () => {
+ const fields = schemaFieldsForDoc(
+ configWithOkf(
+ { enabled: true },
+ {
+ enabled: true,
+ schemas: [
+ {
+ appliesTo: 'notes/**',
+ file: 'notes.json',
+ schema: {
+ type: 'object',
+ required: ['status'],
+ properties: { status: { type: 'string' } },
+ },
+ },
+ ],
+ },
+ ),
+ 'notes/concept',
+ );
+
+ // Both producers' fields are offered side by side.
+ expect(fields.get('status')?.required).toBe(true);
+ expect(fields.get('type')?.required).toBe(true);
+ });
+
+ test('respects the OKF profile scoping (a reserved index gets no concept fields)', () => {
+ // A nested `index` is governed by the reserved-index schema (no properties),
+ // not the concept schemas — the fold must go through the doc-scoped
+ // selector, not blanket-add the whole registry.
+ const fields = schemaFieldsForDoc(configWithOkf({ enabled: true }), 'a/index');
+ expect(fields.has('type')).toBe(false);
+ });
+
+ test('an OKF rule toggled off withdraws its fields', () => {
+ const fields = schemaFieldsForDoc(
+ configWithOkf({ enabled: true, rules: { 'frontmatter-required': false } }),
+ 'notes/concept',
+ );
+ expect(fields.has('type')).toBe(false);
+ // The recommended family stays on independently.
+ expect(fields.get('tags')?.type).toBe('list');
+ });
+
+ test('withholds the profile fields no widget can author conformantly', () => {
+ const fields = schemaFieldsForDoc(configWithOkf({ enabled: true }), 'notes/concept');
+
+ // `sources` is an array of objects each requiring `resource`; the list
+ // widget writes a flat string array, so committing one would be faulted by
+ // the very schema that offered it.
+ expect(fields.has('sources')).toBe(false);
+ // Same shape in the attested-computation family.
+ expect(fields.has('parameters')).toBe(false);
+ // `verified` states two accepted shapes under `anyOf` and no top-level
+ // type, so it would fall to the free-text widget and violate both.
+ expect(fields.has('verified')).toBe(false);
+ });
+
+ test('still offers the profile fields a widget can author', () => {
+ const fields = schemaFieldsForDoc(configWithOkf({ enabled: true }), 'notes/concept');
+
+ // An array of scalars is exactly what the list widget writes.
+ expect(fields.get('tags')?.type).toBe('list');
+ // Enum-only: no declared type, but the picker's vocabulary layer offers the
+ // three values and free text accepts them.
+ expect(fields.get('status')?.type).toBe('text');
+ // Deliberately unconstrained by the profile, so nothing typed can violate it.
+ expect(fields.get('timestamp')?.type).toBe('text');
+ // An object field keeps the nested widget.
+ expect(fields.get('generated')?.type).toBe('object');
+ });
+
+ test('a disabled OKF plugin contributes nothing', () => {
+ const fields = schemaFieldsForDoc(configWithOkf({ enabled: false }), 'notes/concept');
+ expect(fields.has('type')).toBe(false);
+ expect(fields.has('tags')).toBe(false);
+ });
+});
diff --git a/packages/app/src/lib/frontmatter-schema-fields.test.ts b/packages/app/src/lib/frontmatter-schema-fields.test.ts
index a74d55aff..97f5f68f9 100644
--- a/packages/app/src/lib/frontmatter-schema-fields.test.ts
+++ b/packages/app/src/lib/frontmatter-schema-fields.test.ts
@@ -105,6 +105,87 @@ describe('schemaFieldsForDoc', () => {
expect(fields.get('odd')?.type).toBe('text');
});
+ test('an array of non-scalars is not offered at all', () => {
+ // The list widget writes a flat array of scalars, so a row committed for
+ // this field is faulted by the same schema that suggested it.
+ const fields = fieldsFor({
+ type: 'object',
+ properties: {
+ entries: { type: 'array', items: { type: 'object', required: ['resource'] } },
+ nested: { type: 'array', items: { type: 'array' } },
+ },
+ });
+ expect(fields.has('entries')).toBe(false);
+ expect(fields.has('nested')).toBe(false);
+ });
+
+ test('an array that leaves its items open is still offered', () => {
+ // Nothing was stated about the items, so a scalar list violates nothing.
+ expect(
+ fieldsFor({ type: 'object', properties: { any: { type: 'array' } } }).get('any')?.type,
+ ).toBe('list');
+ });
+
+ test('a property constrained only by a composition keyword is not offered', () => {
+ // No top-level type, so it would fall to the free-text widget, which cannot
+ // express either accepted shape.
+ const fields = fieldsFor({
+ type: 'object',
+ properties: {
+ either: { anyOf: [{ type: 'object' }, { type: 'array' }] },
+ exactly: { oneOf: [{ type: 'object' }] },
+ both: { allOf: [{ type: 'object' }] },
+ neither: { not: { type: 'string' } },
+ },
+ });
+ for (const name of ['either', 'exactly', 'both', 'neither']) {
+ expect(fields.has(name)).toBe(false);
+ }
+ });
+
+ test('an enum with no declared type is still offered', () => {
+ // The vocabulary layer offers its values and free text accepts them, so
+ // there is nothing here a committed row can violate.
+ const fields = fieldsFor({
+ type: 'object',
+ properties: { state: { enum: ['draft', 'stable'] } },
+ });
+ expect(fields.get('state')?.type).toBe('text');
+ });
+
+ test('a required field with no authorable widget stays offered', () => {
+ // The missing-property diagnostic stages a row for it regardless, so
+ // withdrawing it from the picker would hide the name and change nothing.
+ const fields = fieldsFor({
+ type: 'object',
+ required: ['entries'],
+ properties: { entries: { type: 'array', items: { type: 'object' } } },
+ });
+ expect(fields.get('entries')).toEqual({ type: 'text', required: true });
+ });
+
+ test('a required field with no authorable widget keeps its description', () => {
+ // It is offered either way, and it is the field the user has least choice
+ // about, so the schema's own hint is the one thing that must survive the
+ // widget being withheld.
+ const fields = fieldsFor({
+ type: 'object',
+ required: ['entries'],
+ properties: {
+ entries: {
+ type: 'array',
+ items: { type: 'object' },
+ description: 'One record per upstream source',
+ },
+ },
+ });
+ expect(fields.get('entries')).toEqual({
+ type: 'text',
+ required: true,
+ description: 'One record per upstream source',
+ });
+ });
+
test('required and description ride along', () => {
const fields = fieldsFor(DOC_SCHEMA);
expect(fields.get('status')).toEqual({
diff --git a/packages/app/src/lib/frontmatter-schema-fields.ts b/packages/app/src/lib/frontmatter-schema-fields.ts
index 00b5fcdf0..b6a383d8e 100644
--- a/packages/app/src/lib/frontmatter-schema-fields.ts
+++ b/packages/app/src/lib/frontmatter-schema-fields.ts
@@ -2,8 +2,9 @@
* Derive the catalogue of fields the schemas governing a doc DECLARE — the
* layer above `frontmatter-enum-constraints`, which derives the allowed VALUES
* of a field already known. Both read the RESOLVED lint config through
- * `selectApplicableFrontmatterSchemas`, so neither can disagree with the linter
- * about which schemas govern a doc.
+ * `selectGoverningFrontmatterSchemas`, so neither can disagree with the linter
+ * about which schemas govern a doc — every frontmatter-capable plugin's
+ * schemas participate, per-plugin enablement and per-rule toggles applied.
*
* Two consumers, both on the add-property path: the field picker offers these
* names so a user does not have to open the schema to learn them, and a row
@@ -26,7 +27,7 @@
import {
type FrontmatterType,
type LinterConfig,
- selectApplicableFrontmatterSchemas,
+ selectGoverningFrontmatterSchemas,
} from '@inkeep/open-knowledge-core';
export interface SchemaField {
@@ -90,17 +91,46 @@ function widgetTypeFor(property: Record<string, unknown>): FrontmatterType | nul
}
}
+/** Item types the `list` widget can write — it produces a flat array of scalars. */
+const AUTHORABLE_LIST_ITEM_TYPES = new Set(['string', 'number', 'integer', 'boolean']);
+
+/** Keywords that constrain a value without naming a type the panel can key a widget off. */
+const TYPELESS_CONSTRAINT_KEYWORDS = ['anyOf', 'oneOf', 'allOf', 'not'];
+
+/**
+ * Whether some widget can author a value this property's schema will accept.
+ *
+ * Offering a field the panel cannot author is worse than not offering it: the
+ * picker names the field, the row commits, and the schema that suggested it
+ * immediately warns on what was just written. Two shapes fail that way — an
+ * array of non-scalars (the list widget writes a flat array of scalars, so an
+ * array of objects can never be satisfied) and a property whose only constraint
+ * is a composition keyword (no top-level type, so it falls to free text, which
+ * cannot express any branch).
+ *
+ * A property that constrains NOTHING is not one of them, and neither is an array
+ * that leaves its items open: free text and a scalar list respectively cannot
+ * violate a constraint that was never stated. An enum is likewise fine — the
+ * picker's sibling vocabulary layer offers its values.
+ */
+function hasAuthorableWidget(property: Record<string, unknown>): boolean {
+ if (property.type === 'array') {
+ const itemType = isRecord(property.items) ? property.items.type : undefined;
+ return typeof itemType !== 'string' || AUTHORABLE_LIST_ITEM_TYPES.has(itemType);
+ }
+ if (typeof property.type === 'string') return true;
+ return !TYPELESS_CONSTRAINT_KEYWORDS.some((keyword) => keyword in property);
+}
+
/** The fields declared for `docName` by every schema that governs it. */
export function schemaFieldsForDoc(
config: LinterConfig | null,
docName: string | undefined,
): Map<string, SchemaField> {
- const slice = config?.plugins.frontmatter;
- if (!config?.enabled || !slice?.enabled || docName === undefined || docName === '') {
- return new Map();
- }
const declared = new Map<string, DeclaredField>();
- const schemas = selectApplicableFrontmatterSchemas(slice.schemas, docName);
+ // Enablement (linting on, producer slices on, per-rule toggles) and doc
+ // scoping all live in the shared selector.
+ const schemas = selectGoverningFrontmatterSchemas(config, docName);
// Unioned up front, not per schema: one schema may declare `status` under
// `properties` while a sibling requires it, and the field is required either
@@ -148,13 +178,25 @@ export function schemaFieldsForDoc(
typeof rawProperty.description === 'string' && rawProperty.description !== ''
? rawProperty.description
: undefined;
+ if (!hasAuthorableWidget(rawProperty)) {
+ // A REQUIRED field is offered whatever its shape (see the loop below),
+ // so skipping it outright costs only the schema's own description —
+ // the one hint the user has for a field they cannot be talked out of.
+ // Its widget stays withheld: `null` resolves to the panel's `text`,
+ // never the widget its declared type names and cannot satisfy.
+ if (required.has(name)) declare(name, null, description);
+ continue;
+ }
declare(name, widgetTypeFor(rawProperty), description);
}
}
// A schema may require a field it never declares under `properties`. The
// picker still has to offer it and a staged row still needs a type, so it
- // lands unconstrained and resolves to text.
+ // lands unconstrained and resolves to text. This runs over the required set
+ // unconditionally, so a REQUIRED field with no authorable widget stays
+ // offered: the missing-property diagnostic will stage a row for it either
+ // way, and withdrawing it from the picker alone would only hide the name.
for (const name of required) declare(name, null);
return new Map(
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index cacd12616..8d7590d1c 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -674,13 +674,16 @@ export {
FrontmatterSchemasListSuccessSchema,
type FrontmatterSchemaWriteRequest,
FrontmatterSchemaWriteRequestSchema,
+ type FrontmatterScope,
type FrontmatterSlice,
findRuleConfigEntry,
findZeroMatchAppliesToPatterns,
fixDocument,
fixMarkdownText,
frontmatterSchemaCompileError,
+ type GoverningFrontmatterSchema,
isFrontmatterSchemaAsset,
+ isFrontmatterScoped,
isMarkdownlintJsonConfig,
isOkfRuleEnabled,
isSupportedSchemaDialect,
@@ -749,7 +752,10 @@ export {
runOkfProjectRules,
type SchemaParentPathSegment,
SUPPORTED_SCHEMA_DIALECTS,
+ selectAdvertisedFrontmatterMappings,
selectApplicableFrontmatterSchemas,
+ selectFrontmatterOnlyConfig,
+ selectGoverningFrontmatterSchemas,
selectOkfFrontmatterSchemas,
summarizeAppliesTo,
toEffectiveBase,
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index 3d4814597..1a81aa524 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -5,6 +5,7 @@ import { DEFAULT_MARKDOWNLINT_CONFIG } from './default-config.ts';
import type { OkfRuleId } from './okf-rule-meta.ts';
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { FrontmatterSchemaMapping, MarkdownlintRuleSetting } from './types.ts';
+import { FRONTMATTER_SCOPES } from './types.ts';
interface PersistedMarkdownlintSlice {
enabled: boolean;
@@ -158,7 +159,7 @@ const LintDiagnosticSchema = z.object({
code: z.string(),
message: z.string(),
fixes: z.array(z.object({ range: LintRangeSchema, newText: z.string() })).optional(),
- frontmatterScope: z.enum(['missing', 'invalid']).optional(),
+ frontmatterScope: z.enum(FRONTMATTER_SCOPES).optional(),
frontmatterProperty: z.string().optional(),
});
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index eba37cee7..5f953d667 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -10,7 +10,12 @@ import {
unwrapFrontmatterFences,
} from '../../extensions/frontmatter.ts';
import { compileAppliesTo } from './applies-to.ts';
-import type { LintDiagnostic, LintPluginId, ResolvedFrontmatterSchemaEntry } from './types.ts';
+import type {
+ FrontmatterScope,
+ LintDiagnostic,
+ LintPluginId,
+ ResolvedFrontmatterSchemaEntry,
+} from './types.ts';
export interface LoadedFrontmatterSchema {
file: string;
@@ -243,7 +248,7 @@ export function validateFrontmatterSource(
if (keyword === 'if') continue;
let line = 0;
let message: string;
- let frontmatterScope: 'missing' | 'invalid' = 'invalid';
+ let frontmatterScope: FrontmatterScope = 'invalid';
let frontmatterProperty: string | undefined;
if (keyword === 'maxProperties' && error.instancePath === '') {
message = 'This document must not have frontmatter';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index ae5ff2924..11b5abdfd 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -124,10 +124,14 @@ export {
} from './okf-rule-meta.ts';
export {
DEFAULT_LINTER_CONFIG,
+ type GoverningFrontmatterSchema,
LINT_PLUGINS,
type LinterConfig,
type LintPlugin,
type LintPluginId,
+ selectAdvertisedFrontmatterMappings,
+ selectFrontmatterOnlyConfig,
+ selectGoverningFrontmatterSchemas,
} from './plugins.ts';
export { canonicalRuleId, findRuleConfigEntry } from './rule-aliases.ts';
export { MARKDOWNLINT_RULE_CATALOG } from './rule-catalog.generated.ts';
@@ -139,6 +143,7 @@ export {
export { applyTextEdits } from './text-edits.ts';
export type {
FrontmatterSchemaMapping,
+ FrontmatterScope,
FrontmatterSlice,
LinksValidationSetting,
LintDiagnostic,
@@ -163,7 +168,11 @@ export type {
ValidationDiagnostic,
ValidationSource,
} from './types.ts';
-export { DEFAULT_LINKS_VALIDATION, LINKS_VALIDATION_SETTINGS } from './types.ts';
+export {
+ DEFAULT_LINKS_VALIDATION,
+ isFrontmatterScoped,
+ LINKS_VALIDATION_SETTINGS,
+} from './types.ts';
export {
countDiagnosticsBySource,
type ValidationCountsBySource,
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
index de09740c5..f325fbbb4 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
@@ -1,6 +1,11 @@
import { compileAppliesTo } from '../applies-to.ts';
import { validateFrontmatterSource } from '../frontmatter-validate.ts';
-import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';
+import {
+ isOkfRuleEnabled,
+ OKF_RULE_IDS,
+ type OkfRuleId,
+ type OkfRuleToggles,
+} from '../okf-rule-meta.ts';
import type { FrontmatterSchemaMapping, LintDiagnostic } from '../types.ts';
import { okfSchemaPathFor } from './paths.ts';
import {
@@ -57,6 +62,12 @@ export const OKF_FRONTMATTER_REGISTRY: readonly OkfFrontmatterEntry[] = [
},
];
+export const OKF_FRONTMATTER_ONLY_TOGGLES: Partial<Record<OkfRuleId, boolean>> = Object.fromEntries(
+ OKF_RULE_IDS.filter((id) => !OKF_FRONTMATTER_REGISTRY.some((entry) => entry.id === id)).map(
+ (id) => [id, false] as const,
+ ),
+);
+
export function selectOkfFrontmatterSchemas(
rules: OkfRuleToggles,
docName: string | undefined,
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 4b9df9c56..09c8450ee 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -5,10 +5,16 @@ import {
validateFrontmatterSource,
} from './frontmatter-validate.ts';
import { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';
-import { runOkfFrontmatterRules } from './okf-frontmatter/registry.ts';
+import {
+ OKF_FRONTMATTER_ONLY_TOGGLES,
+ okfAdvertisedSchemaMappings,
+ runOkfFrontmatterRules,
+ selectOkfFrontmatterSchemas,
+} from './okf-frontmatter/registry.ts';
import { selectEnabledOkfRules } from './okf-rules.ts';
import { runOkfRules } from './okf-runner.ts';
import {
+ type FrontmatterSchemaMapping,
type FrontmatterSlice,
type LintDiagnostic,
type LintPluginId,
@@ -23,12 +29,21 @@ const MarkdownlintRuleSettingSchema = z.union([
z.record(z.string(), z.unknown()),
]);
-export interface LintPlugin<Id extends LintPluginId, Slice> {
+export interface GoverningFrontmatterSchema {
+ schema: Record<string, unknown>;
+}
+
+export interface LintPlugin<Id extends LintPluginId, Slice extends { enabled: boolean }> {
id: Id;
sliceSchema: z.ZodType<Slice>;
defaultSlice: Slice;
lint(text: string, slice: Slice, ctx: { docName?: string }): Promise<LintDiagnostic[]>;
fix?(text: string, slice: Slice): string;
+ frontmatter?: {
+ schemasForDoc(slice: Slice, docName: string): readonly GoverningFrontmatterSchema[];
+ narrowSliceToFrontmatter(slice: Slice): Slice;
+ advertisedMappings(slice: Slice): readonly FrontmatterSchemaMapping[];
+ };
}
const markdownlintPlugin: LintPlugin<'markdownlint', MarkdownlintSlice> = {
@@ -67,6 +82,11 @@ const frontmatterPlugin: LintPlugin<'frontmatter', FrontmatterSlice> = {
selectApplicableFrontmatterSchemas(slice.schemas, ctx.docName),
);
},
+ frontmatter: {
+ schemasForDoc: (slice, docName) => selectApplicableFrontmatterSchemas(slice.schemas, docName),
+ narrowSliceToFrontmatter: (slice) => slice,
+ advertisedMappings: (slice) => slice.schemas,
+ },
};
const okfPlugin: LintPlugin<'okf', OkfSlice> = {
@@ -83,6 +103,14 @@ const okfPlugin: LintPlugin<'okf', OkfSlice> = {
...runOkfFrontmatterRules(text, slice.rules, ctx.docName),
];
},
+ frontmatter: {
+ schemasForDoc: (slice, docName) => selectOkfFrontmatterSchemas(slice.rules, docName),
+ narrowSliceToFrontmatter: (slice) => ({
+ ...slice,
+ rules: { ...slice.rules, ...OKF_FRONTMATTER_ONLY_TOGGLES },
+ }),
+ advertisedMappings: (slice) => okfAdvertisedSchemaMappings(slice.rules),
+ },
};
export const LINT_PLUGINS = [markdownlintPlugin, frontmatterPlugin, okfPlugin] as const;
@@ -106,3 +134,43 @@ export const DEFAULT_LINTER_CONFIG: LinterConfig = {
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.defaultSlice]),
) as LinterConfig['plugins'],
};
+
+export function selectGoverningFrontmatterSchemas(
+ config: LinterConfig | null,
+ docName: string | undefined,
+): GoverningFrontmatterSchema[] {
+ if (!config?.enabled || docName === undefined || docName === '') return [];
+ const governing: GoverningFrontmatterSchema[] = [];
+ for (const plugin of LINT_PLUGINS) {
+ if (plugin.frontmatter === undefined) continue;
+ const slice = config.plugins[plugin.id];
+ if (slice?.enabled !== true) continue;
+ governing.push(...plugin.frontmatter.schemasForDoc(slice as never, docName));
+ }
+ return governing;
+}
+
+export function selectAdvertisedFrontmatterMappings(
+ config: LinterConfig | null,
+): FrontmatterSchemaMapping[] {
+ if (!config?.enabled) return [];
+ const advertised: FrontmatterSchemaMapping[] = [];
+ for (const plugin of LINT_PLUGINS) {
+ if (plugin.frontmatter === undefined) continue;
+ const slice = config.plugins[plugin.id];
+ if (slice?.enabled !== true) continue;
+ advertised.push(...plugin.frontmatter.advertisedMappings(slice as never));
+ }
+ return advertised;
+}
+
+export function selectFrontmatterOnlyConfig(config: LinterConfig): LinterConfig {
+ const plugins = Object.fromEntries(
+ LINT_PLUGINS.map((plugin) => {
+ const slice = config.plugins[plugin.id] ?? plugin.defaultSlice;
+ if (plugin.frontmatter === undefined) return [plugin.id, { ...slice, enabled: false }];
+ return [plugin.id, plugin.frontmatter.narrowSliceToFrontmatter(slice as never)];
+ }),
+ ) as LinterConfig['plugins'];
+ return { ...config, plugins };
+}
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 2a8f4a279..6836b962d 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -21,6 +21,9 @@ export interface LintTextEdit {
newText: string;
}
+export const FRONTMATTER_SCOPES = ['missing', 'invalid'] as const;
+export type FrontmatterScope = (typeof FRONTMATTER_SCOPES)[number];
+
export interface LintDiagnostic {
range: LintRange;
severity: LintSeverity;
@@ -28,10 +31,14 @@ export interface LintDiagnostic {
code: string;
message: string;
fixes?: LintTextEdit[];
- frontmatterScope?: 'missing' | 'invalid';
+ frontmatterScope?: FrontmatterScope;
frontmatterProperty?: string;
}
+export function isFrontmatterScoped(diagnostic: Pick<LintDiagnostic, 'frontmatterScope'>): boolean {
+ return diagnostic.frontmatterScope !== undefined;
+}
+
const VALIDATION_SOURCES = [...LINT_PLUGIN_IDS, 'links'] as const;
export type ValidationSource = (typeof VALIDATION_SOURCES)[number];
diff --git a/packages/server/src/mcp/tools/exec.ts b/packages/server/src/mcp/tools/exec.ts
index 102254abc..3bd67af41 100644
--- a/packages/server/src/mcp/tools/exec.ts
+++ b/packages/server/src/mcp/tools/exec.ts
@@ -21,7 +21,11 @@
*/
import { stat } from 'node:fs/promises';
import { relative, resolve } from 'node:path';
-import { okfAdvertisedSchemaMappings } from '@inkeep/open-knowledge-core';
+import {
+ type PersistedLinterConfig,
+ selectAdvertisedFrontmatterMappings,
+ toEffectiveBase,
+} from '@inkeep/open-knowledge-core';
import { z } from 'zod';
import { argsOf, extractReferencedPaths, nonFlagArgs } from '../../bash/extract-paths.ts';
import { createBashInstance, execBash, StdoutOverflowError } from '../../bash/index.ts';
@@ -578,17 +582,16 @@ export async function buildExecResult(
// Read-time schema advertisement: enrichment resolves which schemas govern each
// listed doc/folder server-side (the agent never evaluates an appliesTo glob).
//
- // Two sources, one list. The frontmatter plugin contributes the project's authored
- // mappings; the OKF plugin contributes its built-in profile, advertised by the
- // `.ok/okf/` path each schema is materialized to so an agent can open the contract.
- // They are concatenated rather than resolved separately so there is a single
- // selection path — a doc governed by both sees both, in plugin-registry order.
- const frontmatterSlice = config.contentRules.frontmatter;
- const okfSlice = config.contentRules.okf;
- const advertisedSchemas = [
- ...(frontmatterSlice.enabled ? frontmatterSlice.schemas : []),
- ...(okfSlice.enabled ? okfAdvertisedSchemaMappings(okfSlice.rules) : []),
- ];
+ // Every enabled frontmatter-producing plugin contributes, in registry order, so a
+ // doc governed by two sees both through one selection path. Which plugins those
+ // are is the registry's answer, not a list here — the frontmatter plugin's
+ // authored mappings and the OKF profile's `.ok/okf/` paths arrive the same way.
+ //
+ // Persisted shape lifted to the effective one the registry reads; `enabled` is
+ // not persisted yet, so the master switch it seeds is on.
+ const advertisedSchemas = selectAdvertisedFrontmatterMappings(
+ toEffectiveBase(config.contentRules as PersistedLinterConfig),
+ );
const enrichSchemaDeps =
advertisedSchemas.length > 0
? {