From 1bff4be201e75d67dca600ad6468db18cf78e3dc Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 1 Dec 2026 22:25:16 +1100 Subject: [PATCH] feat(markdown): coerce strict numeric strings on schema number/integer fields --- src/plugins/markdown/read-space.ts | 3 + src/plugins/markdown/util.ts | 67 +++++++++++++ .../markdown/coerce-numeric-fields.test.ts | 99 +++++++++++++++++++ 3 files changed, 169 insertions(+) create mode 100644 tests/plugins/markdown/coerce-numeric-fields.test.ts diff --git a/src/plugins/markdown/read-space.ts b/src/plugins/markdown/read-space.ts index c098151..ab0f491 100644 --- a/src/plugins/markdown/read-space.ts +++ b/src/plugins/markdown/read-space.ts @@ -12,6 +12,7 @@ import { extractEmbeddedNodes, ON_A_PAGE_TYPES } from './parse-embedded'; import { parseMarkdown } from './parse-markdown'; import { applyFieldMap, + coerceNumericFields, defaultPageTitle, extractYamlFieldSources, inferTypeFromPath, @@ -64,6 +65,7 @@ export function readSpaceOnAPage(context: PluginContext): ParseResult { embedded: mdCfg.embedded, }); + coerceNumericFields(nodes, context); return { nodes, parseIssues: [], diagnostics: { kind: 'page', preambleNodeCount } }; } @@ -233,6 +235,7 @@ export async function readSpaceDirectory( } } + coerceNumericFields(nodes, context); return { nodes, parseIssues, diff --git a/src/plugins/markdown/util.ts b/src/plugins/markdown/util.ts index 9a1de79..ebb821b 100644 --- a/src/plugins/markdown/util.ts +++ b/src/plugins/markdown/util.ts @@ -1,4 +1,5 @@ import { posix } from 'node:path'; +import type { AnySchemaObject } from 'ajv'; import { binaryTag, CORE_SCHEMA, @@ -14,6 +15,10 @@ import { visit, } from 'js-yaml'; import { isMap, isScalar, isSeq, LineCounter, parseDocument } from 'yaml'; +import { resolveNodeType } from '../../schema/schema'; +import { mergeVariantProperties } from '../../schema/schema-refs'; +import type { BaseNode, SchemaWithMetadata } from '../../types'; +import type { PluginContext } from '../util'; import type { TypeInferenceConfig } from '.'; export function inferTypeFromPath( @@ -242,3 +247,65 @@ export function defaultPageTitle(file: string, folderIndex: string[] | undefined if (folder !== undefined && folderIndex?.some((name) => name.toLowerCase() === base.toLowerCase())) return folder; return base; } + +const STRICT_NUMERIC_STRING = /^-?\d+(?:\.\d+)?$/; + +function isNumericSchemaType(prop: AnySchemaObject | undefined): boolean { + if (!prop) return false; + const type = prop.type; + if (type === 'number' || type === 'integer') return true; + if (Array.isArray(type)) { + return (type.includes('number') || type.includes('integer')) && !type.includes('string'); + } + return false; +} + +function numericFieldsByType( + schema: SchemaWithMetadata, + schemaRefRegistry: Map, +): Map> { + const byType = new Map>(); + for (const variant of schema.oneOf ?? []) { + const merged = mergeVariantProperties(variant, schema, schemaRefRegistry); + const typeProp = merged.properties.type; + const typeNames: string[] = []; + if (typeof typeProp?.const === 'string') typeNames.push(typeProp.const); + if (Array.isArray(typeProp?.enum)) { + for (const v of typeProp.enum) { + if (typeof v === 'string') typeNames.push(v); + } + } + if (typeNames.length === 0) continue; + const fields = new Set(); + for (const [name, prop] of Object.entries(merged.properties)) { + if (isNumericSchemaType(prop)) fields.add(name); + } + if (fields.size > 0) { + for (const typeName of typeNames) byType.set(typeName, fields); + } + } + return byType; +} + +/** + * Coerce strict numeric strings (e.g. `"5"`, `"-2.5"`) to numbers on fields whose schema type is + * `number` or `integer`. Non-numeric strings are left untouched so schema validation reports them. + */ +export function coerceNumericFields(nodes: BaseNode[], context: PluginContext): void { + const byType = numericFieldsByType(context.schema, context.schemaRefRegistry); + if (byType.size === 0) return; + const aliases = context.schema.metadata.typeAliases; + for (const node of nodes) { + if (!node.type) continue; + const fields = byType.get(resolveNodeType(node.type, aliases)); + if (!fields) continue; + for (const field of fields) { + const raw = node.schemaData[field]; + if (typeof raw !== 'string') continue; + const trimmed = raw.trim(); + if (!STRICT_NUMERIC_STRING.test(trimmed)) continue; + const num = Number(trimmed); + if (Number.isFinite(num)) node.schemaData[field] = num; + } + } +} diff --git a/tests/plugins/markdown/coerce-numeric-fields.test.ts b/tests/plugins/markdown/coerce-numeric-fields.test.ts new file mode 100644 index 0000000..3e0440a --- /dev/null +++ b/tests/plugins/markdown/coerce-numeric-fields.test.ts @@ -0,0 +1,99 @@ +import { afterEach, describe, expect, it } from 'bun:test'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { assembleSpaceGraph, createSpaceContext, validateSpace } from '../../../src/api'; + +describe('markdown numeric string coercion', () => { + const tmpDirs: string[] = []; + const makeDir = () => { + const dir = mkdtempSync(join(tmpdir(), 'sctx-num-coerce-')); + tmpDirs.push(dir); + return dir; + }; + + afterEach(() => { + while (tmpDirs.length > 0) rmSync(tmpDirs.pop()!, { recursive: true, force: true }); + }); + + it('coerces strict numeric strings on number/integer fields across frontmatter and inline fields, while leaving string and invalid values untouched', async () => { + const dir = makeDir(); + writeFileSync( + join(dir, 'Vision.md'), + `--- +type: vision +status: active +summary: "42" +--- + +## Embedded Goal [type:: goal] [status:: active] [order:: 2.5] +`, + ); + writeFileSync( + join(dir, 'Goal B.md'), + `--- +type: goal +status: active +parent: "[[Vision]]" +order: "10" +--- +`, + ); + writeFileSync( + join(dir, 'Goal A.md'), + `--- +type: goal +status: active +parent: "[[Vision]]" +order: "1" +--- +`, + ); + writeFileSync( + join(dir, 'Opp.md'), + `--- +type: opportunity +status: active +parent: "[[Goal A]]" +impact: "4" +--- +`, + ); + writeFileSync( + join(dir, 'Bad Order.md'), + `--- +type: goal +status: active +parent: "[[Vision]]" +order: "not-a-number" +--- +`, + ); + + const context = createSpaceContext( + 'test', + { spaces: [{ name: 'test', path: dir, schema: 'strategy_general.json' }] }, + { configDir: dir }, + ); + const result = await validateSpace(context); + const graph = await assembleSpaceGraph(context); + + // Non-numeric string still fails schema validation + const schemaErrors = result.issues.filter((i) => i.kind === 'schema'); + expect(schemaErrors).toHaveLength(1); + expect(schemaErrors[0]?.nodeId as string).toBe('Bad Order.md'); + + // Valid numeric strings coerced to numbers and sorted ascending + const visionChildren = graph.hierarchyChildren.get('Vision.md' as never) ?? []; + expect(visionChildren.map((n) => [n.title, n.schemaData.order])).toEqual([ + ['Goal A', 1], + ['Embedded Goal', 2.5], + ['Goal B', 10], + ['Bad Order', 'not-a-number'], + ]); + + // Integer field coerced; string field with digits left as string + expect(graph.nodes.get('Opp.md' as never)?.schemaData.impact).toBe(4); + expect(graph.nodes.get('Vision.md' as never)?.schemaData.summary).toBe('42'); + }); +});