Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): accept JSON Schema dialects beyond draft-07 (#2948)
serafin-garciad00e9420eedd
diff --git a/.changeset/frontmatter-schema-dialects.md b/.changeset/frontmatter-schema-dialects.mdnew file mode 100644index 000000000..a7325b601--- /dev/null+++ b/.changeset/frontmatter-schema-dialects.md@@ -0,0 +1,20 @@+---+"@inkeep/open-knowledge-core": minor+"@inkeep/open-knowledge-server": minor+"@inkeep/open-knowledge-app": minor+"@inkeep/open-knowledge": minor+---++Frontmatter schemas now accept draft-06, 2019-09, and 2020-12 in addition to draft-07.++**Any of four dialects, validated against its own rules.** A schema file declaring `draft-06`, `draft-07`, `2019-09`, or `2020-12` is compiled against that dialect, so `$defs`, `prefixItems`, `dependentRequired`, and the rest behave as their spec says rather than being ignored. Each URI is accepted in `http` or `https` form, with or without the trailing `#`. Previously anything but draft-07 was skipped entirely with a configuration problem telling you to downgrade — a 2020-12 schema, which has been the current dialect since 2020, got you no validation at all.++**An absent `$schema` still means draft-07, and that is still what gets scaffolded.** Creating a schema from Settings ▸ Plugins ▸ Frontmatter schemas writes the draft-07 skeleton as before: it is the most broadly supported dialect among external tools, and the friendly subset the Fields editor writes is spelled identically in all four. Nothing about an existing project changes.++**`format` keeps asserting on every dialect.** From 2019-09 on, the spec demotes `format` to an annotation validators may ignore. OK asserts it everywhere instead, so raising a schema's `$schema` line never silently switches off format checks it already had. This is deliberately stricter than the spec.++**Dialects older than draft-06 are still skipped**, now with a configuration problem that names what is supported instead of demanding draft-07.++**Fixed: editing a schema that declares `$id` silently stopped it validating.** The validator instance outlives any one schema and registers each compiled schema under its `$id`, so recompiling an edited file whose `$id` was unchanged was refused — and because compile failures are swallowed by design, the governed documents just quietly stopped reporting violations until the process restarted. The stale registration is now dropped before recompiling. This bug predates dialect support and affected draft-07 schemas equally, but `$id` alongside `$defs` is idiomatic in 2019-09 and 2020-12, so it would have been far easier to hit.++The no-code Fields editor and the property panel needed no changes: both were already dialect-agnostic, reading only the friendly subset (`type`, `enum`, `items.enum`, `pattern`, `format`, `description`, `required`) and preserving every other keyword verbatim. A 2020-12 schema opens in Fields and round-trips with its `$defs`, `$id`, `unevaluatedProperties`, and `prefixItems` intact — `prefixItems` is not modeled, so it appears in the existing "advanced rules" note alongside `allOf`.diff --git a/docs/content/advanced/content-rules/frontmatter.mdx b/docs/content/advanced/content-rules/frontmatter.mdxindex b0436e643..c3c78471e 100644--- a/docs/content/advanced/content-rules/frontmatter.mdx+++ b/docs/content/advanced/content-rules/frontmatter.mdx@@ -4,7 +4,7 @@ icon: LuBracesdescription: Validate document frontmatter against standard JSON Schema files — scoped to folders with globs, with schema-driven selects in the property panel and a no-code schema editor.----Frontmatter schemas is a content-rules linter that validates each document's YAML frontmatter against [JSON Schema](https://json-schema.org/) (draft-07) files. The schema files are plain, portable JSON Schema — nothing OK-specific in them — so the same files work with any external tool that understands the standard.+Frontmatter schemas is a content-rules linter that validates each document's YAML frontmatter against [JSON Schema](https://json-schema.org/) files. The schema files are plain, portable JSON Schema — nothing OK-specific in them — so the same files work with any external tool that understands the standard.This page covers the schema mappings, the schema files, the no-code editors, and what agents see. For the linter-agnostic parts — where problems appear, the Problems panel, `ok lint`, and agent advisories — see the [content rules overview](/docs/advanced/content-rules/overview).@@ -33,10 +33,29 @@ contentRules:## Schema files-Standard draft-07 only: an absent `$schema` is treated as draft-07, and a file declaring another dialect is skipped with a configuration problem. A schema file that is missing, malformed, or refused by the validator is also a **configuration problem** — it shows at the top of the Problems panel's project scope, in `ok lint` warnings, and on the MCP `lint` tool, never as a per-doc diagnostic.+A schema file that is missing, malformed, or refused by the validator is a **configuration problem** — it shows at the top of the Problems panel's project scope, in `ok lint` warnings, and on the MCP `lint` tool, never as a per-doc diagnostic.A doc with no frontmatter block (or unparsable YAML) validates as an empty object — so `required` fields still report on brand-new docs. The reverse also works: a schema with `"maxProperties": 0` enforces that docs carry no frontmatter at all.+### Dialects++Four dialects are supported, each validated against its own rules:++| `$schema` | Dialect |+| --- | --- |+| `http://json-schema.org/draft-06/schema#` | draft-06 |+| `http://json-schema.org/draft-07/schema#` | draft-07 |+| `https://json-schema.org/draft/2019-09/schema` | 2019-09 |+| `https://json-schema.org/draft/2020-12/schema` | 2020-12 |++Each is accepted in `http` or `https` form, with or without the trailing `#`. An **absent `$schema` is treated as draft-07**, and that is also what **New schema** scaffolds — the widest-compatibility choice, and the friendly subset the Fields editor writes is spelled identically in every dialect. A file declaring anything else (draft-04 and older) is skipped with a configuration problem.++Three things worth knowing:++- **`format` always asserts.** From 2019-09 on, the spec demotes `format` to an annotation that validators may ignore. OK asserts it on every dialect instead, so raising a schema's `$schema` never silently switches off format checks it already had. This is deliberately stricter than the spec.+- **The Fields editor doesn't model `prefixItems`.** 2020-12 spells tuple arrays as `prefixItems`, which the no-code editor leaves alone — it appears in the "advanced rules" note alongside `allOf` and friends, and survives every edit verbatim. Uniform arrays (`items`) are modeled as usual.+- **draft-06 is validated by the draft-07 engine.** draft-07 only added keywords, so every draft-06 construct behaves identically — but the reverse also holds: keywords draft-07 introduced (`if`/`then`/`else`, `readOnly`, `writeOnly`) are honored in a schema that declares draft-06, where a strict draft-06 validator would ignore them. Harmless unless you rely on another tool ignoring them.+## What a finding looks likeTake the schema above governing `docs/**`, and a doc that misses one required field and misspells an enum value:@@ -123,4 +142,4 @@ The server resolves the globs; agents never evaluate `appliesTo` themselves. And- [Content rules overview](/docs/advanced/content-rules/overview): where problems show up, the Problems panel, `ok lint`, and agents- [markdownlint](/docs/advanced/content-rules/markdownlint): the sibling linter for markdown style- [Configuration reference](/docs/reference/configuration): `config.yml` and what's shared via git-- [JSON Schema draft-07](https://json-schema.org/specification-links#draft-7): the schema dialect+- [JSON Schema specification links](https://json-schema.org/specification-links): the supported dialectsdiff --git a/packages/app/src/components/settings/LintingSection.tsx b/packages/app/src/components/settings/LintingSection.tsxindex 5d44e8758..d9235aff5 100644--- a/packages/app/src/components/settings/LintingSection.tsx+++ b/packages/app/src/components/settings/LintingSection.tsx@@ -613,9 +613,9 @@ export function FrontmatterPluginSection() {beta><Trans>- Validate document frontmatter against standard JSON Schema files (draft-07). Toggle a- schema on to validate the docs its globs match; violations surface as warnings and never- block a write. Use Edit to open the schema file.+ Validate document frontmatter against standard JSON Schema files (draft-06, draft-07,+ 2019-09, or 2020-12). Toggle a schema on to validate the docs its globs match; violations+ surface as warnings and never block a write. Use Edit to open the schema file.</Trans></PluginSectionHeader>diff --git a/packages/app/src/editor/lint-config-client.ts b/packages/app/src/editor/lint-config-client.tsindex 23a08e9e5..cb2815e49 100644--- a/packages/app/src/editor/lint-config-client.ts+++ b/packages/app/src/editor/lint-config-client.ts@@ -220,7 +220,7 @@ async function listFrontmatterSchemas(): Promise<string[]> {/*** POST a create-empty request to the schema write endpoint (no field) —- * scaffolds `<file>` with the draft-07 skeleton if it doesn't exist yet, so+ * scaffolds `<file>` with the default-dialect skeleton if it doesn't exist yet, so* the picker's "create new schema" lands a real, valid file. Idempotent* server-side (an existing file is left untouched). Emits* `emitLintConfigChanged()` on success so the picker list + open editors refresh.diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 1632be70b..aaa9468e4 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -647,9 +647,6 @@],"C-xgad": ["or use a starter pack"],"C0hoX6": ["Always included"],- "C52RBg": [- "Validate document frontmatter against standard JSON Schema files (draft-07). Toggle a schema on to validate the docs its globs match; violations surface as warnings and never block a write. Use Edit to open the schema file."- ],"C62P6b": ["Editor selection"],"C7XjNB": ["Global Skill"],"C9TBvF": ["No Outgoing"],@@ -1645,6 +1642,9 @@["configFile"],"</0> file, which fully governs linting for this project. Turn rules on or off and edit their options here; changes write back to the file."],+ "V3iDh1": [+ "Validate document frontmatter against standard JSON Schema files (draft-06, draft-07, 2019-09, or 2020-12). Toggle a schema on to validate the docs its globs match; violations surface as warnings and never block a write. Use Edit to open the schema file."+ ],"V48OUT": ["You deleted <0>", ["filePath"], "</0> locally, but it was modified upstream."],"V6AIOn": ["Workspace navigation"],"V7QxyT": ["Connection dropped"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex cba617502..aa32f8ea5 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -10172,8 +10172,8 @@ msgid "Validate document frontmatter against JSON Schema files, scoped to doc semsgstr "Validate document frontmatter against JSON Schema files, scoped to doc sets by glob."#: src/components/settings/LintingSection.tsx-msgid "Validate document frontmatter against standard JSON Schema files (draft-07). Toggle a schema on to validate the docs its globs match; violations surface as warnings and never block a write. Use Edit to open the schema file."-msgstr "Validate document frontmatter against standard JSON Schema files (draft-07). Toggle a schema on to validate the docs its globs match; violations surface as warnings and never block a write. Use Edit to open the schema file."+msgid "Validate document frontmatter against standard JSON Schema files (draft-06, draft-07, 2019-09, or 2020-12). Toggle a schema on to validate the docs its globs match; violations surface as warnings and never block a write. Use Edit to open the schema file."+msgstr "Validate document frontmatter against standard JSON Schema files (draft-06, draft-07, 2019-09, or 2020-12). Toggle a schema on to validate the docs its globs match; violations surface as warnings and never block a write. Use Edit to open the schema file."#: src/components/FrontmatterRow.tsxmsgid "Value for {keyName}"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 6d55e34c1..b76e70f6e 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -647,9 +647,6 @@],"C-xgad": ["ōŕ ũśē à śţàŕţēŕ ƥàćķ"],"C0hoX6": ["Àĺŵàŷś ĩńćĺũďēď"],- "C52RBg": [- "Vàĺĩďàţē ďōćũḿēńţ ƒŕōńţḿàţţēŕ àĝàĩńśţ śţàńďàŕď ĵŚŌŃ Śćĥēḿà ƒĩĺēś (ďŕàƒţ-07). Ţōĝĝĺē à śćĥēḿà ōń ţō vàĺĩďàţē ţĥē ďōćś ĩţś ĝĺōƀś ḿàţćĥ; vĩōĺàţĩōńś śũŕƒàćē àś ŵàŕńĩńĝś àńď ńēvēŕ ƀĺōćķ à ŵŕĩţē. Ũśē Ēďĩţ ţō ōƥēń ţĥē śćĥēḿà ƒĩĺē."- ],"C62P6b": ["Ēďĩţōŕ śēĺēćţĩōń"],"C7XjNB": ["Ĝĺōƀàĺ Śķĩĺĺ"],"C9TBvF": ["Ńō Ōũţĝōĩńĝ"],@@ -1645,6 +1642,9 @@["configFile"],"</0> ƒĩĺē, ŵĥĩćĥ ƒũĺĺŷ ĝōvēŕńś ĺĩńţĩńĝ ƒōŕ ţĥĩś ƥŕōĴēćţ. Ţũŕń ŕũĺēś ōń ōŕ ōƒƒ àńď ēďĩţ ţĥēĩŕ ōƥţĩōńś ĥēŕē; ćĥàńĝēś ŵŕĩţē ƀàćķ ţō ţĥē ƒĩĺē."],+ "V3iDh1": [+ "Vàĺĩďàţē ďōćũḿēńţ ƒŕōńţḿàţţēŕ àĝàĩńśţ śţàńďàŕď ĵŚŌŃ Śćĥēḿà ƒĩĺēś (ďŕàƒţ-06, ďŕàƒţ-07, 2019-09, ōŕ 2020-12). Ţōĝĝĺē à śćĥēḿà ōń ţō vàĺĩďàţē ţĥē ďōćś ĩţś ĝĺōƀś ḿàţćĥ; vĩōĺàţĩōńś śũŕƒàćē àś ŵàŕńĩńĝś àńď ńēvēŕ ƀĺōćķ à ŵŕĩţē. Ũśē Ēďĩţ ţō ōƥēń ţĥē śćĥēḿà ƒĩĺē."+ ],"V48OUT": ["Ŷōũ ďēĺēţēď <0>", ["filePath"], "</0> ĺōćàĺĺŷ, ƀũţ ĩţ ŵàś ḿōďĩƒĩēď ũƥśţŕēàḿ."],"V6AIOn": ["Ŵōŕķśƥàćē ńàvĩĝàţĩōń"],"V7QxyT": ["Ćōńńēćţĩōń ďŕōƥƥēď"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex b7e366a22..b4c6adda2 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -10168,7 +10168,7 @@ msgid "Validate document frontmatter against JSON Schema files, scoped to doc semsgstr ""#: src/components/settings/LintingSection.tsx-msgid "Validate document frontmatter against standard JSON Schema files (draft-07). Toggle a schema on to validate the docs its globs match; violations surface as warnings and never block a write. Use Edit to open the schema file."+msgid "Validate document frontmatter against standard JSON Schema files (draft-06, draft-07, 2019-09, or 2020-12). Toggle a schema on to validate the docs its globs match; violations surface as warnings and never block a write. Use Edit to open the schema file."msgstr ""#: src/components/FrontmatterRow.tsxdiff --git a/packages/app/tests/dom/frontmatter-dialects-client-realm.dom.test.tsx b/packages/app/tests/dom/frontmatter-dialects-client-realm.dom.test.tsxnew file mode 100644index 000000000..ccb375815--- /dev/null+++ b/packages/app/tests/dom/frontmatter-dialects-client-realm.dom.test.tsx@@ -0,0 +1,125 @@+/**+ * The frontmatter validator is isomorphic: the editor runs it client-side via+ * `useDocDiagnostics` -> `lintDocument`, so the 2019-09 and 2020-12 ajv entry+ * points are bundled into the browser build, not just the server. Both are+ * CommonJS, and the compile path swallows a failure to `null` — so a+ * module-interop break in the client realm would surface as *zero* frontmatter+ * diagnostics in the editor while `ok lint`, the HTTP API, and MCP all keep+ * working. That asymmetry is invisible without a test that constructs the+ * engines outside Node's realm.+ *+ * It mounts a probe that awaits `lintDocument` in an effect and renders the+ * resulting codes — the same shape `useDocDiagnostics` uses — rather than+ * calling the validator inline, so the engines are exercised through a real+ * React render in jsdom. Asserting concrete codes (not merely "it didn't+ * throw") is what makes it discriminating: the swallow-to-null path yields an+ * empty array, exactly what a broken engine produces.+ */++import {+ DEFAULT_LINTER_CONFIG,+ type LinterConfig,+ lintDocument,+} from '@inkeep/open-knowledge-core';+import { cleanup, render, screen } from '@testing-library/react';+import { useEffect, useState } from 'react';+import { afterEach, describe, expect, test } from 'vitest';++afterEach(cleanup);++const DOC_NAME = 'docs/guide';+const PENDING = 'pending';++function configFor(schema: Record<string, unknown>): LinterConfig {+ return {+ ...DEFAULT_LINTER_CONFIG,+ enabled: true,+ plugins: {+ ...DEFAULT_LINTER_CONFIG.plugins,+ markdownlint: { ...DEFAULT_LINTER_CONFIG.plugins.markdownlint, enabled: false },+ frontmatter: {+ enabled: true,+ schemas: [{ appliesTo: 'docs/**', file: '.ok/schemas/probe.schema.json', schema }],+ },+ },+ };+}++/** Mirrors how `useDocDiagnostics` drives the linter: await it in an effect. */+function DiagnosticsProbe({ text, schema }: { text: string; schema: Record<string, unknown> }) {+ const [codes, setCodes] = useState<string | null>(null);+ useEffect(() => {+ let cancelled = false;+ void lintDocument(text, configFor(schema), DOC_NAME).then((diagnostics) => {+ if (cancelled) return;+ setCodes(+ diagnostics+ .filter((d) => d.source === 'frontmatter')+ .map((d) => d.code)+ .sort()+ .join(','),+ );+ });+ return () => {+ cancelled = true;+ };+ }, [text, schema]);+ return <output data-testid="codes">{codes ?? PENDING}</output>;+}++async function mountAndReadCodes(text: string, schema: Record<string, unknown>): Promise<string> {+ render(<DiagnosticsProbe text={text} schema={schema} />);+ const node = await screen.findByTestId('codes');+ // The probe starts at PENDING; wait for the effect's promise to land so an+ // engine that never resolves fails here instead of reading as "no findings".+ await expect.poll(() => node.textContent).not.toBe(PENDING);+ return node.textContent ?? '';+}++describe('frontmatter dialects in the client realm', () => {+ test('jsdom is the active environment (guards against a silent node-realm run)', () => {+ expect(typeof document).toBe('object');+ expect(typeof window).toBe('object');+ });++ test('2020-12 compiles and validates client-side (prefixItems + asserted format)', async () => {+ const doc = ['---', 'reviewedAt: not-a-date', 'pair:', ' - ok', ' - nope', '---'].join('\n');+ // `format` proves ajv-formats attached to the 2020-12 instance; `type` on+ // `pair.1` proves prefixItems (a 2020-12-only keyword) actually compiled.+ expect(+ await mountAndReadCodes(doc, {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ reviewedAt: { type: 'string', format: 'date' },+ pair: { type: 'array', prefixItems: [{ type: 'string' }, { type: 'number' }] },+ },+ }),+ ).toBe('format,type');+ });++ test('2019-09 compiles and validates client-side (dependentRequired + $defs/$ref)', async () => {+ expect(+ await mountAndReadCodes('---\nslug: Bad Slug\n---\n', {+ $schema: 'https://json-schema.org/draft/2019-09/schema',+ type: 'object',+ $defs: { Slug: { type: 'string', pattern: '^[a-z-]+$' } },+ properties: { slug: { $ref: '#/$defs/Slug' } },+ dependentRequired: { slug: ['owner'] },+ }),+ ).toBe('dependentRequired,pattern');+ });++ test.each([+ 'http://json-schema.org/draft-06/schema#',+ 'http://json-schema.org/draft-07/schema#',+ ])('%s still validates client-side', async ($schema) => {+ expect(+ await mountAndReadCodes('---\nweight: 5\n---\n', {+ $schema,+ type: 'object',+ properties: { weight: { type: 'number', exclusiveMinimum: 5 } },+ }),+ ).toBe('exclusiveMinimum');+ });+});diff --git a/packages/app/tests/integration/frontmatter-lint-http.test.ts b/packages/app/tests/integration/frontmatter-lint-http.test.tsindex b65e26ea0..6d79c7a2b 100644--- a/packages/app/tests/integration/frontmatter-lint-http.test.ts+++ b/packages/app/tests/integration/frontmatter-lint-http.test.ts@@ -30,6 +30,10 @@ const SEED_CONFIG = [' file: ".ok/schemas/doc.schema.json"',' - appliesTo: "broken/**"',' file: ".ok/schemas/missing.schema.json"',+ ' - appliesTo: "modern/**"',+ ' file: ".ok/schemas/modern.schema.json"',+ ' - appliesTo: "nineteen/**"',+ ' file: ".ok/schemas/nineteen.schema.json"','',].join('\n');@@ -43,6 +47,31 @@ const DOC_SCHEMA = {},};+// 2020-12, exercising the keywords draft-07 cannot express: `$defs` with a+// `$ref`, and a `prefixItems` tuple.+const MODERN_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ $defs: { Status: { enum: ['draft', 'review', 'published'] } },+ required: ['owner', 'status'],+ properties: {+ owner: { type: 'string' },+ status: { $ref: '#/$defs/Status' },+ pair: { type: 'array', prefixItems: [{ type: 'string' }, { type: 'number' }] },+ },+};++// 2019-09 runs on a different ajv class (Ajv2019) than 2020-12 (Ajv2020), so the+// server load -> HTTP diagnostic path is proven for both, not just the newest.+const NINETEEN_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2019-09/schema',+ type: 'object',+ $defs: { Slug: { type: 'string', pattern: '^[a-z-]+$' } },+ required: ['slug'],+ properties: { slug: { $ref: '#/$defs/Slug' } },+ dependentRequired: { slug: ['owner'] },+};+const VIOLATING_DOC = ['---', 'status: shipped', '---', '', '# Guide'].join('\n');beforeAll(async () => {@@ -53,9 +82,41 @@ beforeAll(async () => {JSON.stringify(DOC_SCHEMA, null, 2),'utf-8',);+ writeFileSync(+ join(server.contentDir, '.ok', 'schemas', 'modern.schema.json'),+ JSON.stringify(MODERN_SCHEMA, null, 2),+ 'utf-8',+ );mkdirSync(join(server.contentDir, 'docs'), { recursive: true });writeFileSync(join(server.contentDir, 'docs', 'guide.md'), VIOLATING_DOC, 'utf-8');writeFileSync(join(server.contentDir, 'docs', 'index.md'), VIOLATING_DOC, 'utf-8');+ writeFileSync(+ join(server.contentDir, '.ok', 'schemas', 'nineteen.schema.json'),+ JSON.stringify(NINETEEN_SCHEMA, null, 2),+ 'utf-8',+ );+ mkdirSync(join(server.contentDir, 'nineteen'), { recursive: true });+ writeFileSync(+ join(server.contentDir, 'nineteen', 'note.md'),+ ['---', 'slug: Bad Slug', '---', '', '# Note'].join('\n'),+ 'utf-8',+ );+ mkdirSync(join(server.contentDir, 'modern'), { recursive: true });+ writeFileSync(+ join(server.contentDir, 'modern', 'spec.md'),+ [+ '---',+ 'owner: serafin',+ 'status: shipped',+ 'pair:',+ ' - ok',+ ' - nope',+ '---',+ '',+ '# Spec',+ ].join('\n'),+ 'utf-8',+ );}, HARNESS_BOOT_TIMEOUT_MS);afterAll(async () => {@@ -88,6 +149,49 @@ describe('GET /api/lint — frontmatter diagnostics', () => {expect(body.diagnostics.filter((d) => d.source === 'frontmatter')).toEqual([]);});+ /**+ * A dialect newer than draft-07 loads and validates over the wire — the+ * whole path (loader dialect check, per-dialect ajv, HTTP shape), not just+ * the pure validator.+ *+ */+ test('a 2020-12 schema validates, including $defs/$ref and prefixItems', async () => {+ const res = await fetch(api('/api/lint?doc=modern%2Fspec'));+ expect(res.status).toBe(200);+ const body = LintDocResultSchema.parse(await res.json());+ const frontmatter = body.diagnostics.filter((d) => d.source === 'frontmatter');++ // No config problem for this mapping — the dialect is supported now.+ expect(body.warnings?.some((w) => w.includes('modern.schema.json'))).toBe(false);++ const enumViolation = frontmatter.find((d) => d.code === 'enum');+ expect(enumViolation?.message).toContain('draft, review, published');+ expect(enumViolation?.range.start.line).toBe(2);++ const tuple = frontmatter.find((d) => d.code === 'type');+ expect(tuple?.message).toContain('"pair.1"');+ expect(tuple?.range.start.line).toBe(3);+ });++ /**+ * 2019-09 compiles on `Ajv2019`, a different class than 2020-12's `Ajv2020`.+ * Proving only the newest dialect over the wire would leave a per-class+ * wiring failure invisible at this tier.+ *+ */+ test('a 2019-09 schema validates, including $defs/$ref and dependentRequired', async () => {+ const res = await fetch(api('/api/lint?doc=nineteen%2Fnote'));+ expect(res.status).toBe(200);+ const body = LintDocResultSchema.parse(await res.json());+ const frontmatter = body.diagnostics.filter((d) => d.source === 'frontmatter');++ expect(body.warnings?.some((w) => w.includes('nineteen.schema.json'))).toBe(false);+ expect(frontmatter.map((d) => d.code).sort()).toEqual(['dependentRequired', 'pattern']);++ const pattern = frontmatter.find((d) => d.code === 'pattern');+ expect(pattern?.range.start.line).toBe(1);+ });+test('single-doc responses carry the schemaError on the additive warnings channel, never per-doc', async () => {const res = await fetch(api('/api/lint?doc=docs%2Fguide'));const body = LintDocResultSchema.parse(await res.json());diff --git a/packages/cli/src/content/lint-runner.test.ts b/packages/cli/src/content/lint-runner.test.tsindex 0f36c6f5a..8990fcb02 100644--- a/packages/cli/src/content/lint-runner.test.ts+++ b/packages/cli/src/content/lint-runner.test.ts@@ -192,6 +192,29 @@ describe('runLint — frontmatter schemas', () => {expect(index?.diagnostics.filter((d) => d.source === 'frontmatter')).toEqual([]);});+ test('a 2020-12 schema validates through the CLI path too', async () => {+ write(+ '.ok/schemas/modern.schema.json',+ JSON.stringify({+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ $defs: { Status: { enum: ['draft', 'published'] } },+ properties: { status: { $ref: '#/$defs/Status' } },+ required: ['status'],+ }),+ );+ write('docs/guide.md', '---\nstatus: shipped\n---\n\n# Guide\n');+ const result = await run({+ baseConfig: frontmatterBase([+ { appliesTo: 'docs/**', file: '.ok/schemas/modern.schema.json' },+ ]),+ });+ expect(result.warnings).toEqual([]);+ const guide = result.files.find((f) => f.file === join('docs', 'guide.md'));+ expect(guide?.diagnostics.map((d) => `${d.source}/${d.code}`)).toEqual(['frontmatter/enum']);+ expect(guide?.diagnostics[0]?.range.start.line).toBe(1);+ });+test('schemaError surfaces as a report warning and never flips diagnostics', async () => {write('docs/guide.md', '---\nstatus: draft\n---\n');const result = await run({diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.tsindex 20851d630..1215ab391 100644--- a/packages/core/src/config/schema.ts+++ b/packages/core/src/config/schema.ts@@ -739,8 +739,8 @@ export const ConfigSchema = z.looseObject({}).default(false),// Schema CONTENT is NOT persisted here. Each entry scopes one- // standard draft-07 JSON Schema file (project-root-relative `file`,- // portable to any external tool) to a set of docs via `appliesTo`+ // standard JSON Schema file (project-root-relative `file`, portable+ // to any external tool) to a set of docs via `appliesTo`// globs (single or list; leading `!` excludes; absent matches every// doc). Loaded server/CLI-side and injected into the effective// config; entry order carries no precedence — every match validates.diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex a60aa6818..4b24755d2 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -500,15 +500,18 @@ export {type AppliesToSummary,applyFieldConstraint,applyTextEdits,+ CANONICAL_SCHEMA_DIALECT_URIS,type CompiledAppliesTo,canonicalRuleId,compileAppliesTo,DEFAULT_LINKS_VALIDATION,DEFAULT_LINTER_CONFIG,DEFAULT_MARKDOWNLINT_CONFIG,+ DEFAULT_SCHEMA_DIALECT,displayCategoryForRule,emptyFrontmatterSchemaText,type FrontmatterFieldConstraint,+ type FrontmatterSchemaDialect,FrontmatterSchemaEditError,type FrontmatterSchemaMapping,type FrontmatterSchemasListSuccess,@@ -563,9 +566,11 @@ export {type RuleOptionType,removeSchemaField,renameSchemaField,+ resolveFrontmatterSchemaDialect,resolveMarkdownlintConfig,runMarkdownlint,type SchemaParentPathSegment,+ SUPPORTED_SCHEMA_DIALECTS,selectApplicableFrontmatterSchemas,summarizeAppliesTo,toEffectiveBase,diff --git a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.tsindex 74226af8e..ef478e268 100644--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts@@ -1,4 +1,4 @@-import { DRAFT07_SCHEMA_URIS } from './frontmatter-validate.ts';+import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';export interface FrontmatterFieldConstraint {type?: 'string' | 'number' | 'boolean' | 'array' | 'object' | null;@@ -14,7 +14,8 @@ export interface FrontmatterFieldConstraint {export type SchemaParentPathSegment = string | { items: true };export function emptyFrontmatterSchemaText(): string {- return `${JSON.stringify({ $schema: DRAFT07_SCHEMA_URIS[0], type: 'object' }, null, 2)}\n`;+ const $schema = CANONICAL_SCHEMA_DIALECT_URIS[DEFAULT_SCHEMA_DIALECT];+ return `${JSON.stringify({ $schema, type: 'object' }, null, 2)}\n`;}export function isToolManagedSchemaPath(file: string): boolean {diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.tsindex 176822faf..3871ccada 100644--- a/packages/core/src/markdown/lint/frontmatter-validate.ts+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts@@ -1,4 +1,7 @@import Ajv, { type ValidateFunction } from 'ajv';+import Ajv2019 from 'ajv/dist/2019.js';+import Ajv2020 from 'ajv/dist/2020.js';+import type AjvCore from 'ajv/dist/core.js';import addFormats from 'ajv-formats';import { isMap, isScalar, parseDocument } from 'yaml';import {@@ -32,29 +35,88 @@ export function selectApplicableFrontmatterSchemas(return selected;}-export const DRAFT07_SCHEMA_URIS = [- 'http://json-schema.org/draft-07/schema#',- 'http://json-schema.org/draft-07/schema',- 'https://json-schema.org/draft-07/schema#',- 'https://json-schema.org/draft-07/schema',-] as const;+export type FrontmatterSchemaDialect = 'draft-06' | 'draft-07' | '2019-09' | '2020-12';-export function isSupportedSchemaDialect(schema: Record<string, unknown>): boolean {+export const CANONICAL_SCHEMA_DIALECT_URIS: Record<FrontmatterSchemaDialect, string> = {+ 'draft-06': 'http://json-schema.org/draft-06/schema#',+ 'draft-07': 'http://json-schema.org/draft-07/schema#',+ '2019-09': 'https://json-schema.org/draft/2019-09/schema',+ '2020-12': 'https://json-schema.org/draft/2020-12/schema',+};++export const SUPPORTED_SCHEMA_DIALECTS = Object.keys(+ CANONICAL_SCHEMA_DIALECT_URIS,+) as readonly FrontmatterSchemaDialect[];++export const DEFAULT_SCHEMA_DIALECT: FrontmatterSchemaDialect = 'draft-07';++const DIALECT_BY_NORMALIZED_URI = new Map<string, FrontmatterSchemaDialect>(+ SUPPORTED_SCHEMA_DIALECTS.map((dialect) => [+ normalizeDialectUri(CANONICAL_SCHEMA_DIALECT_URIS[dialect]),+ dialect,+ ]),+);++function normalizeDialectUri(uri: string): string {+ return uri.replace(/^https?:\/\//, '').replace(/#$/, '');+}++export function resolveFrontmatterSchemaDialect(+ schema: Record<string, unknown>,+): FrontmatterSchemaDialect | null {const declared = schema.$schema;- if (declared === undefined) return true;- return (- typeof declared === 'string' && (DRAFT07_SCHEMA_URIS as readonly string[]).includes(declared)- );+ if (declared === undefined) return DEFAULT_SCHEMA_DIALECT;+ if (typeof declared !== 'string') return null;+ return DIALECT_BY_NORMALIZED_URI.get(normalizeDialectUri(declared)) ?? null;+}++export function isSupportedSchemaDialect(schema: Record<string, unknown>): boolean {+ return resolveFrontmatterSchemaDialect(schema) !== null;}-let ajvInstance: Ajv | null = null;+const ajvByDialect = new Map<FrontmatterSchemaDialect, AjvCore>();++function assertNeverDialect(dialect: never): never {+ throw new Error(`Unhandled FrontmatterSchemaDialect: ${JSON.stringify(dialect as unknown)}`);+}-function getAjv(): Ajv {- if (!ajvInstance) {- ajvInstance = new Ajv({ allErrors: true, strict: false });- addFormats(ajvInstance);+function getAjv(dialect: FrontmatterSchemaDialect): AjvCore {+ const existing = ajvByDialect.get(dialect);+ if (existing) return existing;+ const options = { allErrors: true, strict: false };+ let created: AjvCore;+ switch (dialect) {+ case '2020-12':+ created = new Ajv2020(options);+ break;+ case '2019-09':+ created = new Ajv2019(options);+ break;+ case 'draft-06':+ case 'draft-07':+ created = new Ajv(options);+ break;+ default:+ return assertNeverDialect(dialect);}- return ajvInstance;+ (addFormats as (ajv: AjvCore) => void)(created);+ ajvByDialect.set(dialect, created);+ return created;+}++function schemaBodyForAjv(schema: Record<string, unknown>): Record<string, unknown> {+ const { $schema: _declared, ...body } = schema;+ return body;+}++function compileOnDialect(+ dialect: FrontmatterSchemaDialect,+ schema: Record<string, unknown>,+): ValidateFunction {+ const ajv = getAjv(dialect);+ const declaredId = schema.$id;+ if (typeof declaredId === 'string' && declaredId !== '') ajv.removeSchema(declaredId);+ return ajv.compile(schemaBodyForAjv(schema));}const compiledByContent = new Map<string, ValidateFunction | null>();@@ -65,10 +127,10 @@ function compileSchema(schema: Record<string, unknown>): ValidateFunction | nullconst cached = compiledByContent.get(key);if (cached !== undefined) return cached;let compiled: ValidateFunction | null = null;- if (isSupportedSchemaDialect(schema)) {- const { $schema: _dialect, ...body } = schema;+ const dialect = resolveFrontmatterSchemaDialect(schema);+ if (dialect !== null) {try {- compiled = getAjv().compile(body);+ compiled = compileOnDialect(dialect, schema);} catch {compiled = null;}@@ -80,9 +142,10 @@ function compileSchema(schema: Record<string, unknown>): ValidateFunction | nullexport function frontmatterSchemaCompileError(schema: Record<string, unknown>): string | null {if (compileSchema(schema)) return null;- const { $schema: _dialect, ...body } = schema;+ const dialect = resolveFrontmatterSchemaDialect(schema);+ if (dialect === null) return `unsupported dialect ${JSON.stringify(schema.$schema)}`;try {- getAjv().compile(body);+ compileOnDialect(dialect, schema);return 'schema was refused';} catch (err) {return err instanceof Error ? err.message : String(err);diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.tsindex d458fea1f..ce0db23a3 100644--- a/packages/core/src/markdown/lint/index.ts+++ b/packages/core/src/markdown/lint/index.ts@@ -73,8 +73,13 @@ export {type SchemaParentPathSegment,} from './frontmatter-schema-edit.ts';export {+ CANONICAL_SCHEMA_DIALECT_URIS,+ DEFAULT_SCHEMA_DIALECT,+ type FrontmatterSchemaDialect,frontmatterSchemaCompileError,isSupportedSchemaDialect,+ resolveFrontmatterSchemaDialect,+ SUPPORTED_SCHEMA_DIALECTS,selectApplicableFrontmatterSchemas,} from './frontmatter-validate.ts';export { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';diff --git a/packages/server/src/lint/frontmatter-schema-write.ts b/packages/server/src/lint/frontmatter-schema-write.tsindex 5b9611b73..ad6b842e4 100644--- a/packages/server/src/lint/frontmatter-schema-write.ts+++ b/packages/server/src/lint/frontmatter-schema-write.ts@@ -1,7 +1,8 @@/*** Frontmatter schema-file WRITE surface: merge one field's constraints into a* schema file via the core `applyFieldConstraint` (non-destructive — advanced- * keywords survive verbatim), creating the file with the draft-07 skeleton on+ * keywords survive verbatim), creating the file with the default-dialect+ * skeleton on* first edit. Same safety posture as the markdownlint writer: project-root* escape guarding (lexical + realpath), atomic tmp+rename through the traced* fs wrappers, and a typed refusal instead of a throw for policy declines.@@ -103,7 +104,7 @@ export function writeFrontmatterSchemaField(}/**- * Scaffold an empty schema file (the draft-07 skeleton) at `file` if it does+ * Scaffold an empty schema file (the default-dialect skeleton) at `file` if it does* not already exist — the create-empty half of the write surface, so the* picker's "create new schema" lands a real, valid file before any field is* added. Idempotent: an existing file is left untouched (never clobbered).diff --git a/packages/server/src/lint/frontmatter-schemas.test.ts b/packages/server/src/lint/frontmatter-schemas.test.tsindex d9ef4d056..2165de278 100644--- a/packages/server/src/lint/frontmatter-schemas.test.ts+++ b/packages/server/src/lint/frontmatter-schemas.test.ts@@ -9,7 +9,13 @@ import {} from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';-import { DEFAULT_LINTER_CONFIG, type LinterConfig } from '@inkeep/open-knowledge-core';+import {+ CANONICAL_SCHEMA_DIALECT_URIS,+ DEFAULT_LINTER_CONFIG,+ DEFAULT_SCHEMA_DIALECT,+ type LinterConfig,+ SUPPORTED_SCHEMA_DIALECTS,+} from '@inkeep/open-knowledge-core';import { afterEach, beforeEach, describe, expect, test } from 'vitest';import {listProjectSchemaFiles,@@ -122,13 +128,41 @@ describe('resolveFrontmatterSchemas — loading', () => {expect(problems[0]).toContain('not a JSON object');});- test('another dialect is skipped with a problem', () => {+ test.each(SUPPORTED_SCHEMA_DIALECTS)('a %s schema loads cleanly', (dialect) => {+ write(+ 'dialect.json',+ JSON.stringify({+ $schema: CANONICAL_SCHEMA_DIALECT_URIS[dialect],+ type: 'object',+ required: ['title'],+ }),+ );+ const { entries, problems } = resolveFrontmatterSchemas(projectDir, [{ file: 'dialect.json' }]);+ expect(problems).toEqual([]);+ expect(entries[0]?.schema).toMatchObject({ required: ['title'] });+ });++ test('a schema with no $schema loads (absent means the default dialect)', () => {+ write('bare.json', JSON.stringify({ type: 'object', required: ['title'] }));+ const { entries, problems } = resolveFrontmatterSchemas(projectDir, [{ file: 'bare.json' }]);+ expect(problems).toEqual([]);+ expect(entries[0]?.schema).toMatchObject({ required: ['title'] });+ });++ test('an unsupported dialect is skipped with a problem naming what is supported', () => {write(- '2020.json',- JSON.stringify({ $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'object' }),+ 'draft04.json',+ JSON.stringify({ $schema: 'http://json-schema.org/draft-04/schema#', type: 'object' }),);- const { entries, problems } = resolveFrontmatterSchemas(projectDir, [{ file: '2020.json' }]);+ const { entries, problems } = resolveFrontmatterSchemas(projectDir, [{ file: 'draft04.json' }]);expect(problems[0]).toContain('unsupported dialect');+ expect(problems[0]).toContain('draft-04');+ for (const dialect of SUPPORTED_SCHEMA_DIALECTS) {+ expect(problems[0]).toContain(dialect);+ }+ // The message carries a paste-ready canonical `$schema` URI, not just the+ // dialect labels, so the fix reads off directly.+ expect(problems[0]).toContain(CANONICAL_SCHEMA_DIALECT_URIS[DEFAULT_SCHEMA_DIALECT]);expect(entries[0]?.schema).toBeUndefined();});diff --git a/packages/server/src/lint/frontmatter-schemas.ts b/packages/server/src/lint/frontmatter-schemas.tsindex 889e1174b..ca276bdce 100644--- a/packages/server/src/lint/frontmatter-schemas.ts+++ b/packages/server/src/lint/frontmatter-schemas.ts@@ -3,7 +3,7 @@* mapping names a JSON Schema file by a path relative to the PROJECT ROOT* (the folder containing `.ok/` — not `contentDir`, so the `.ok/schemas/`* default keeps working when `content.dir` scopes docs to a subfolder). This- * loads each file once, validates the draft-07 dialect pin, and injects the+ * loads each file once, validates the declared dialect, and injects the* parsed content + a canonical dedup key into the resolved entries the core* plugin (and the browser, via the effective config) validates with.*@@ -19,12 +19,15 @@import { readdirSync, readFileSync, realpathSync } from 'node:fs';import { join, resolve } from 'node:path';import {+ CANONICAL_SCHEMA_DIALECT_URIS,compileAppliesTo,+ DEFAULT_SCHEMA_DIALECT,type FrontmatterSchemaMapping,findZeroMatchAppliesToPatterns,frontmatterSchemaCompileError,isSupportedSchemaDialect,type ResolvedFrontmatterSchemaEntry,+ SUPPORTED_SCHEMA_DIALECTS,} from '@inkeep/open-knowledge-core';import { getLogger } from '../logger.ts';import { isInside } from './fs-safety.ts';@@ -146,8 +149,12 @@ function loadSchemaFile(projectDir: string, file: string): LoadOutcome {}const schema = parsed as Record<string, unknown>;if (!isSupportedSchemaDialect(schema)) {+ // Name the supported dialects (the overview) and one paste-ready canonical+ // `$schema` URI (a concrete fix), so the author doesn't have to translate a+ // label back into the exact string to write.+ const example = JSON.stringify(CANONICAL_SCHEMA_DIALECT_URIS[DEFAULT_SCHEMA_DIALECT]);return {- problem: `frontmatter schema ${file}: unsupported dialect ${JSON.stringify(schema.$schema)} (draft-07 required)`,+ problem: `frontmatter schema ${file}: unsupported dialect ${JSON.stringify(schema.$schema)} (supported: ${SUPPORTED_SCHEMA_DIALECTS.join(', ')}; e.g. ${example})`,};}const compileError = frontmatterSchemaCompileError(schema);