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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/plugins/markdown/read-space.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { extractEmbeddedNodes, ON_A_PAGE_TYPES } from './parse-embedded';
import { parseMarkdown } from './parse-markdown';
import {
applyFieldMap,
coerceNumericFields,
defaultPageTitle,
extractYamlFieldSources,
inferTypeFromPath,
Expand Down Expand Up @@ -64,6 +65,7 @@ export function readSpaceOnAPage(context: PluginContext): ParseResult {
embedded: mdCfg.embedded,
});

coerceNumericFields(nodes, context);
return { nodes, parseIssues: [], diagnostics: { kind: 'page', preambleNodeCount } };
}

Expand Down Expand Up @@ -233,6 +235,7 @@ export async function readSpaceDirectory(
}
}

coerceNumericFields(nodes, context);
return {
nodes,
parseIssues,
Expand Down
67 changes: 67 additions & 0 deletions src/plugins/markdown/util.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { posix } from 'node:path';
import type { AnySchemaObject } from 'ajv';
import {
binaryTag,
CORE_SCHEMA,
Expand All @@ -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(
Expand Down Expand Up @@ -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<string, AnySchemaObject>,
): Map<string, Set<string>> {
const byType = new Map<string, Set<string>>();
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<string>();
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;
}
}
}
99 changes: 99 additions & 0 deletions tests/plugins/markdown/coerce-numeric-fields.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});