From e7fb4657e966a5c9fe9cf21b77a409f8ceda35bd Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 1 Dec 2026 07:53:11 +1100 Subject: [PATCH 1/3] Add built-in JSON/JSONL parse plugin with multi-parser merging --- docs/config.md | 7 + src/plugins/builtin-names.ts | 1 + src/plugins/index.ts | 9 +- src/plugins/json/index.ts | 216 +++++++++++++++++++++++++++ src/plugins/markdown/index.ts | 1 + src/read/read-space.ts | 41 ++++- tests/plugins/json/read-json.test.ts | 141 +++++++++++++++++ tests/plugins/loader.test.ts | 11 +- 8 files changed, 419 insertions(+), 8 deletions(-) create mode 100644 src/plugins/json/index.ts create mode 100644 tests/plugins/json/read-json.test.ts diff --git a/docs/config.md b/docs/config.md index 715e4cb9..80731a6a 100644 --- a/docs/config.md +++ b/docs/config.md @@ -251,6 +251,13 @@ Controls how headings, lists and tables inside a node become embedded nodes, key - **`tables`** — set to `true` to extract embedded table-row nodes (default `false`; markdown tables stay as node content). - **`yamlBlocks`** — set to `true` to merge fenced `yaml` code blocks into node fields (default `false`; fenced `yaml` blocks stay as node content). +## JSON plugin config + +The built-in `json` plugin (`sctx-json`) runs alongside `sctx-markdown` by default and parses `.json` files (a single node object or an array of node objects) and `.jsonl` files (one node object per line) in the space. Set under `plugins.json` per space: + +- **`enabled`** — set to `false` to ignore `.json` and `.jsonl` files in the space (default `true`). +- **`fieldMap`** — maps source JSON property names to canonical schema field names. + ## Filter views Named filter expressions can be defined per space under `views`. Each view has an `expression` field: diff --git a/src/plugins/builtin-names.ts b/src/plugins/builtin-names.ts index bb4e37ee..f8ff34a5 100644 --- a/src/plugins/builtin-names.ts +++ b/src/plugins/builtin-names.ts @@ -4,6 +4,7 @@ import { normalizePluginName } from './util'; /** Names of the plugins bundled with structured-context. Each built-in plugin takes its `name` from here. */ export const BUILTIN_PLUGIN_NAMES = { markdown: `${PLUGIN_PREFIX}markdown`, + json: `${PLUGIN_PREFIX}json`, mermaid: `${PLUGIN_PREFIX}mermaid`, mapViews: `${PLUGIN_PREFIX}map-views`, miro: `${PLUGIN_PREFIX}miro`, diff --git a/src/plugins/index.ts b/src/plugins/index.ts index 1f327e32..6711e435 100644 --- a/src/plugins/index.ts +++ b/src/plugins/index.ts @@ -1,3 +1,4 @@ +import { jsonPlugin } from './json'; import { mapViewsPlugin } from './map-views'; import { markdownPlugin } from './markdown'; import { mermaidPlugin } from './mermaid'; @@ -5,4 +6,10 @@ import { miroPlugin } from './miro'; import type { StructuredContextPlugin } from './util'; /** All built-in plugins, in default load order. */ -export const builtinPlugins: StructuredContextPlugin[] = [markdownPlugin, mermaidPlugin, miroPlugin, mapViewsPlugin]; +export const builtinPlugins: StructuredContextPlugin[] = [ + markdownPlugin, + jsonPlugin, + mermaidPlugin, + miroPlugin, + mapViewsPlugin, +]; diff --git a/src/plugins/json/index.ts b/src/plugins/json/index.ts new file mode 100644 index 00000000..1b54aaac --- /dev/null +++ b/src/plugins/json/index.ts @@ -0,0 +1,216 @@ +import { existsSync, readFileSync, statSync } from 'node:fs'; +import { basename, join, resolve } from 'node:path'; +import fg from 'fast-glob'; +import type { FromSchema } from 'json-schema-to-ts'; +import type { BaseNode, NodeId, ParseIssue } from '../../types'; +import { BUILTIN_PLUGIN_NAMES } from '../builtin-names'; +import type { ParseOptions, ParseResult, PluginContext, StructuredContextPlugin } from '../util'; + +const JSON_CONFIG_SCHEMA = { + type: 'object', + properties: { + enabled: { type: 'boolean' }, + fieldMap: { type: 'object', additionalProperties: { type: 'string' } }, + }, + additionalProperties: false, +} as const; + +type JsonPluginConfig = FromSchema; + +function isJsonFile(file: string): boolean { + const lower = file.toLowerCase(); + return lower.endsWith('.json') || lower.endsWith('.jsonl'); +} + +function isPlainObject(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function applyFieldMap( + data: Record, + fieldMap: Record | undefined, +): Record { + if (!fieldMap || Object.keys(fieldMap).length === 0) return data; + const result: Record = {}; + for (const [key, value] of Object.entries(data)) { + result[fieldMap[key] ?? key] = value; + } + return result; +} + +function pathLinkTargets(file: string): string[] { + const segments = file + .replace(/\\/g, '/') + .replace(/\.jsonl?$/i, '') + .split('/'); + return segments.map((_, i) => segments.slice(i).join('/')); +} + +function recordToNode( + raw: unknown, + file: string, + fallbackId: string, + line: number, + fieldMap: Record | undefined, + extraTargets: string[], + parseIssues: ParseIssue[], +): BaseNode | null { + if (!isPlainObject(raw)) { + parseIssues.push({ + source: { file, line }, + severity: 'warning', + type: 'no-type', + message: 'Expected a JSON object for node', + }); + return null; + } + + const data = applyFieldMap(raw, fieldMap); + if (typeof data.type !== 'string' || data.type.trim() === '') { + parseIssues.push({ + source: { file, line }, + severity: 'warning', + type: 'no-type', + message: 'No type specified', + }); + return null; + } + + const explicitId = typeof data.id === 'string' && data.id.trim() !== '' ? data.id : undefined; + const id = (explicitId ?? fallbackId) as NodeId; + const explicitTitle = typeof data.title === 'string' ? data.title : undefined; + const title = explicitTitle ?? (typeof data.name === 'string' ? data.name : id); + + return { + id, + title, + schemaData: { title, ...data }, + linkTargets: [...new Set([id, ...(explicitTitle !== undefined ? [explicitTitle] : []), ...extraTargets])], + type: data.type, + source: { file, line }, + ...(typeof data.content === 'string' ? { content: data.content } : {}), + }; +} + +function parseJsonFile( + file: string, + content: string, + fieldMap: Record | undefined, + nodes: BaseNode[], + parseIssues: ParseIssue[], +): void { + const isJsonl = file.toLowerCase().endsWith('.jsonl'); + + if (isJsonl) { + const lines = content.split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const trimmed = lines[i]!.trim(); + if (!trimmed) continue; + const lineNumber = i + 1; + let parsed: unknown; + try { + parsed = JSON.parse(trimmed); + } catch (err) { + parseIssues.push({ + source: { file, line: lineNumber }, + severity: 'error', + type: 'parse', + message: err instanceof Error ? err.message : String(err), + }); + continue; + } + const node = recordToNode(parsed, file, `${file}:${lineNumber}`, lineNumber, fieldMap, [], parseIssues); + if (node) nodes.push(node); + } + return; + } + + let parsed: unknown; + try { + parsed = JSON.parse(content); + } catch (err) { + parseIssues.push({ + source: { file, line: 1 }, + severity: 'error', + type: 'parse', + message: err instanceof Error ? err.message : String(err), + }); + return; + } + + if (Array.isArray(parsed)) { + for (let i = 0; i < parsed.length; i++) { + const node = recordToNode(parsed[i], file, `${file}#${i}`, 1, fieldMap, [], parseIssues); + if (node) nodes.push(node); + } + return; + } + + const node = recordToNode(parsed, file, file, 1, fieldMap, pathLinkTargets(file), parseIssues); + if (node) nodes.push(node); +} + +async function parse(context: PluginContext, options?: ParseOptions): Promise { + const cfg = (context.pluginConfig ?? {}) as JsonPluginConfig; + if (cfg.enabled === false) return null; + + const spacePath = context.space.path; + if (!existsSync(spacePath)) return null; + + const stat = statSync(spacePath); + const nodes: BaseNode[] = []; + const parseIssues: ParseIssue[] = []; + + if (stat.isFile()) { + if (!isJsonFile(spacePath)) return null; + const file = basename(spacePath); + const content = readFileSync(spacePath, 'utf-8'); + parseJsonFile(file, content, cfg.fieldMap, nodes, parseIssues); + return { + nodes, + parseIssues, + diagnostics: { kind: 'file' }, + }; + } + + const resolvedSchema = resolve(context.resolvedSchemaPath); + const isPartial = options?.files !== undefined; + let files: string[]; + + if (options?.files !== undefined) { + const relevant = options.files.filter( + (rel) => isJsonFile(rel) && !rel.split(/[\\/]/).some((segment) => segment.startsWith('.')), + ); + if (relevant.length === 0) return null; + files = relevant.filter((rel) => { + const abs = resolve(spacePath, rel); + return abs !== resolvedSchema && existsSync(abs) && statSync(abs).isFile(); + }); + } else { + const found = await fg(['**/*.json', '**/*.jsonl'], { + cwd: spacePath, + followSymbolicLinks: true, + ignore: ['**/node_modules/**'], + }); + files = found.filter((rel) => resolve(spacePath, rel) !== resolvedSchema); + if (files.length === 0) return null; + } + + for (const file of files) { + const content = readFileSync(join(spacePath, file), 'utf-8'); + parseJsonFile(file, content, cfg.fieldMap, nodes, parseIssues); + } + + return { + nodes, + parseIssues, + diagnostics: { kind: 'directory' }, + ...(isPartial ? { partial: true } : {}), + }; +} + +export const jsonPlugin: StructuredContextPlugin = { + name: BUILTIN_PLUGIN_NAMES.json, + configSchema: JSON_CONFIG_SCHEMA, + parse, +}; diff --git a/src/plugins/markdown/index.ts b/src/plugins/markdown/index.ts index cad298d3..1564ce02 100644 --- a/src/plugins/markdown/index.ts +++ b/src/plugins/markdown/index.ts @@ -64,6 +64,7 @@ export function getMarkdownConfig(plugins?: Record { if (statSync(context.space.path).isFile()) { + if (!context.space.path.toLowerCase().endsWith('.md')) return null; return readSpaceOnAPage(context); } return await readSpaceDirectory(context, options?.files ? { files: options.files } : undefined); diff --git a/src/read/read-space.ts b/src/read/read-space.ts index 6227e2d5..7795f374 100644 --- a/src/read/read-space.ts +++ b/src/read/read-space.ts @@ -1,3 +1,4 @@ +import { isBuiltinPluginName } from '../plugins/builtin-names'; import { loadPlugins } from '../plugins/loader'; import type { ParseOptions, ParseResult } from '../plugins/util'; import type { BaseNode, ReadSpaceResult, SpaceContext } from '../types'; @@ -29,6 +30,10 @@ function toReadSpaceResult( }; } +function hasParsedContent(result: ParseResult): boolean { + return result.nodes.length > 0 || result.parseIssues.length > 0 || (result.excludedPages?.length ?? 0) > 0; +} + async function dispatchParse( context: SpaceContext, options?: ParseOptions, @@ -36,15 +41,47 @@ async function dispatchParse( const pluginMap: Record> = context.space?.plugins ?? {}; const loaded = await loadPlugins(pluginMap, context.configDir); + // Non-built-in parse plugins take precedence (first match wins). for (const { plugin, pluginConfig } of loaded) { - if (!plugin.parse) continue; + if (!plugin.parse || isBuiltinPluginName(plugin.name)) continue; const result = await plugin.parse({ ...context, pluginConfig }, options); if (result !== null) { return { source: plugin.name, result }; } } - throw new Error(`No plugin handled space at: ${context.space.path}`); + // Built-in filesystem parse plugins (e.g. markdown + json) run together and merge their results. + const matched: Array<{ name: string; result: ParseResult }> = []; + for (const { plugin, pluginConfig } of loaded) { + if (!plugin.parse || !isBuiltinPluginName(plugin.name)) continue; + const result = await plugin.parse({ ...context, pluginConfig }, options); + if (result !== null) { + matched.push({ name: plugin.name, result }); + } + } + + if (matched.length === 0) { + throw new Error(`No plugin handled space at: ${context.space.path}`); + } + if (matched.length === 1) { + return { source: matched[0]!.name, result: matched[0]!.result }; + } + + const active = matched.filter((m) => hasParsedContent(m.result)); + const sourceNames = (active.length > 0 ? active : matched).map((m) => m.name); + const excludedPages = matched.flatMap((m) => m.result.excludedPages ?? []); + const diagnostics = Object.assign({}, ...matched.map((m) => m.result.diagnostics)); + + return { + source: sourceNames.join(', '), + result: { + nodes: matched.flatMap((m) => m.result.nodes), + parseIssues: matched.flatMap((m) => m.result.parseIssues), + ...(excludedPages.length > 0 ? { excludedPages } : {}), + diagnostics, + ...(matched.every((m) => m.result.partial) ? { partial: true } : {}), + }, + }; } export async function readSpace(context: SpaceContext): Promise { diff --git a/tests/plugins/json/read-json.test.ts b/tests/plugins/json/read-json.test.ts new file mode 100644 index 00000000..bef0f30f --- /dev/null +++ b/tests/plugins/json/read-json.test.ts @@ -0,0 +1,141 @@ +import { afterAll, describe, expect, it } from 'bun:test'; +import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { Config } from '../../../src/config'; +import { readSpace, refreshReadResult } from '../../../src/read/read-space'; +import { createSpaceContext } from '../../../src/space-context'; + +const META = + 'https://raw.githubusercontent.com/mindsocket/structured-context/main/schemas/generated/latest/_structured_context_schema_meta.json'; + +describe('built-in JSON/JSONL parse plugin', () => { + const dir = mkdtempSync(join(tmpdir(), 'sctx-json-plugin-')); + afterAll(() => rmSync(dir, { recursive: true, force: true })); + + const schemaContent = JSON.stringify({ + $schema: META, + $id: 'sctx://json-plugin.test', + $metadata: { + hierarchy: { + levels: [{ type: 'goal' }, { type: 'task' }], + }, + }, + oneOf: [ + { + type: 'object', + properties: { type: { const: 'goal' }, title: { type: 'string' } }, + required: ['type', 'title'], + }, + { + type: 'object', + properties: { + type: { const: 'task' }, + title: { type: 'string' }, + parent: { type: 'string' }, + content: { type: 'string' }, + }, + required: ['type', 'title'], + }, + ], + }); + + const mixedDir = join(dir, 'mixed'); + mkdirSync(mixedDir, { recursive: true }); + // Place schema inside the space directory to verify it is skipped as a node file. + const schemaPath = join(mixedDir, 'schema.json'); + writeFileSync(schemaPath, schemaContent); + + writeFileSync(join(mixedDir, 'RootGoal.md'), ['---', 'type: goal', '---', ''].join('\n')); + writeFileSync( + join(mixedDir, 'single.json'), + JSON.stringify({ type: 'task', title: 'Single JSON Task', parent: '[[RootGoal]]' }), + ); + writeFileSync( + join(mixedDir, 'batch.json'), + JSON.stringify([ + { id: 'task-a', type: 'task', title: 'Batch A', parent: '[[RootGoal]]', content: 'Body text' }, + { title: 'Missing type item' }, + ]), + ); + writeFileSync( + join(mixedDir, 'stream.jsonl'), + [ + JSON.stringify({ id: 'line-1', type: 'task', title: 'Line One', parent: '[[RootGoal]]' }), + '', + '{ invalid json', + JSON.stringify({ type: 'task', title: 'Line Four', parent: '[[single]]' }), + ].join('\n'), + ); + + const makeCtx = (path: string, plugins?: Record>) => { + const config: Config = { + spaces: [{ name: 'test', path, schema: schemaPath, ...(plugins ? { plugins } : {}) }], + }; + return createSpaceContext('test', config, { configDir: dir }); + }; + + it('merges markdown, JSON, and JSONL nodes in a directory and resolves cross-format links', async () => { + const result = await readSpace(makeCtx(mixedDir)); + expect(result.source).toBe('sctx-markdown, sctx-json'); + + const titles = result.nodes.map((n) => n.title).sort(); + expect(titles).toEqual(['Batch A', 'Line Four', 'Line One', 'RootGoal', 'Single JSON Task']); + + // Cross-format links resolve between JSON/JSONL nodes and markdown/JSON targets + const singleTask = result.nodes.find((n) => n.title === 'Single JSON Task'); + expect(singleTask?.resolvedParents.map((p) => String(p.id))).toEqual(['RootGoal.md']); + + const lineFour = result.nodes.find((n) => n.title === 'Line Four'); + expect(lineFour?.resolvedParents.map((p) => String(p.id))).toEqual(['single.json']); + + const batchA = result.nodes.find((n) => String(n.id) === 'task-a'); + expect(batchA?.content).toBe('Body text'); + + // Parse issues report invalid JSONL line numbers and missing-type items + expect(result.parseIssues).toContainEqual( + expect.objectContaining({ type: 'parse', severity: 'error', source: { file: 'stream.jsonl', line: 3 } }), + ); + expect(result.parseIssues).toContainEqual( + expect.objectContaining({ type: 'no-type', severity: 'warning', source: { file: 'batch.json', line: 1 } }), + ); + }); + + it('reads a single .jsonl file space directly', async () => { + const result = await readSpace(makeCtx(join(mixedDir, 'stream.jsonl'))); + expect(result.source).toBe('sctx-json'); + expect(result.nodes.map((n) => n.title)).toEqual(['Line One', 'Line Four']); + }); + + it('supports plugins.json.fieldMap and plugins.json.enabled: false', async () => { + const mappedDir = join(dir, 'mapped'); + mkdirSync(mappedDir, { recursive: true }); + writeFileSync(join(mappedDir, 'items.json'), JSON.stringify([{ kind: 'goal', title: 'Mapped Goal' }])); + + const mapped = await readSpace(makeCtx(mappedDir, { json: { fieldMap: { kind: 'type' } } })); + expect(mapped.nodes.map((n) => n.title)).toEqual(['Mapped Goal']); + + const disabled = await readSpace(makeCtx(mappedDir, { json: { enabled: false } })); + expect(disabled.nodes).toEqual([]); + expect(disabled.source).toBe('sctx-markdown'); + }); + + it('updates and deletes JSON nodes during incremental refresh', async () => { + const watchDir = join(dir, 'watch'); + mkdirSync(watchDir, { recursive: true }); + writeFileSync(join(watchDir, 'Goal.md'), ['---', 'type: goal', '---', ''].join('\n')); + writeFileSync(join(watchDir, 'tasks.jsonl'), `${JSON.stringify({ id: 't1', type: 'task', title: 'First' })}\n`); + + const ctx = makeCtx(watchDir); + const initial = await readSpace(ctx); + expect(initial.nodes.map((n) => n.title).sort()).toEqual(['First', 'Goal']); + + writeFileSync(join(watchDir, 'tasks.jsonl'), `${JSON.stringify({ id: 't1', type: 'task', title: 'Updated' })}\n`); + const updated = await refreshReadResult(ctx, initial, ['tasks.jsonl']); + expect(updated.nodes.map((n) => n.title).sort()).toEqual(['Goal', 'Updated']); + + unlinkSync(join(watchDir, 'tasks.jsonl')); + const deleted = await refreshReadResult(ctx, updated, ['tasks.jsonl']); + expect(deleted.nodes.map((n) => n.title)).toEqual(['Goal']); + }); +}); diff --git a/tests/plugins/loader.test.ts b/tests/plugins/loader.test.ts index 8f002d52..da587b33 100644 --- a/tests/plugins/loader.test.ts +++ b/tests/plugins/loader.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'bun:test'; import { join } from 'node:path'; +import { BUILTIN_PLUGIN_NAMES } from '../../src/plugins/builtin-names'; import { loadPlugins } from '../../src/plugins/loader'; // configDir points at tests/fixtures/ so convention resolution looks in tests/fixtures/.sctx/plugins/ @@ -9,11 +10,11 @@ describe('loadPlugins', () => { describe('built-in plugins', () => { it('always includes built-in plugins when no map is given', async () => { const loaded = await loadPlugins({}, CONFIG_DIR); - expect(loaded).toHaveLength(4); - expect(loaded.map((l) => l.plugin.name)).toContain('sctx-markdown'); - expect(loaded.map((l) => l.plugin.name)).toContain('sctx-mermaid'); - expect(loaded.map((l) => l.plugin.name)).toContain('sctx-miro'); - expect(loaded.map((l) => l.plugin.name)).toContain('sctx-map-views'); + const expectedNames = Object.values(BUILTIN_PLUGIN_NAMES); + expect(loaded).toHaveLength(expectedNames.length); + for (const name of expectedNames) { + expect(loaded.map((l) => l.plugin.name)).toContain(name); + } expect(loaded.find((l) => l.plugin.name === 'sctx-markdown')!.pluginConfig).toEqual({}); expect(loaded.find((l) => l.plugin.name === 'sctx-mermaid')!.pluginConfig).toEqual({}); expect(loaded.find((l) => l.plugin.name === 'sctx-miro')!.pluginConfig).toEqual({}); From caede51c12e952b3423f2f8ee7c9624ebce37610 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 1 Dec 2026 08:32:02 +1100 Subject: [PATCH 2/3] Make JSON plugin opt-in via space.plugins with path and include options --- docs/config.md | 21 ++++++++- src/plugins/json/index.ts | 65 ++++++++++++++++++++-------- tests/plugins/json/read-json.test.ts | 48 ++++++++++++++------ 3 files changed, 99 insertions(+), 35 deletions(-) diff --git a/docs/config.md b/docs/config.md index 80731a6a..bc708929 100644 --- a/docs/config.md +++ b/docs/config.md @@ -253,9 +253,26 @@ Controls how headings, lists and tables inside a node become embedded nodes, key ## JSON plugin config -The built-in `json` plugin (`sctx-json`) runs alongside `sctx-markdown` by default and parses `.json` files (a single node object or an array of node objects) and `.jsonl` files (one node object per line) in the space. Set under `plugins.json` per space: +Enable the built-in `json` plugin (`sctx-json`) per space under `plugins.json` to parse `.json` files (a single node object or an array of node objects) and `.jsonl` files (one node object per line) alongside markdown: -- **`enabled`** — set to `false` to ignore `.json` and `.jsonl` files in the space (default `true`). +```json +{ + "spaces": [ + { + "name": "my-space", + "path": "/path/to/space", + "plugins": { + "json": {} + } + } + ] +} +``` + +With an empty config (`{}`), the plugin scans the space's `path` for `**/*.json` and `**/*.jsonl`. Optional fields: + +- **`path`** — directory or single `.json`/`.jsonl` file to read instead of the space's `path` (relative paths resolve from the config root). +- **`include`** — glob patterns relative to `path` (default `["**/*.json", "**/*.jsonl"]`). - **`fieldMap`** — maps source JSON property names to canonical schema field names. ## Filter views diff --git a/src/plugins/json/index.ts b/src/plugins/json/index.ts index 1b54aaac..4c80f698 100644 --- a/src/plugins/json/index.ts +++ b/src/plugins/json/index.ts @@ -1,15 +1,24 @@ import { existsSync, readFileSync, statSync } from 'node:fs'; -import { basename, join, resolve } from 'node:path'; +import { basename, isAbsolute, join, relative, resolve } from 'node:path'; import fg from 'fast-glob'; import type { FromSchema } from 'json-schema-to-ts'; import type { BaseNode, NodeId, ParseIssue } from '../../types'; import { BUILTIN_PLUGIN_NAMES } from '../builtin-names'; -import type { ParseOptions, ParseResult, PluginContext, StructuredContextPlugin } from '../util'; +import { + type ParseOptions, + type ParseResult, + type PluginContext, + type StructuredContextPlugin, + shortenPluginName, +} from '../util'; + +const DEFAULT_INCLUDE = ['**/*.json', '**/*.jsonl']; const JSON_CONFIG_SCHEMA = { type: 'object', properties: { - enabled: { type: 'boolean' }, + path: { type: 'string', format: 'path' }, + include: { type: 'array', items: { type: 'string', minLength: 1 } }, fieldMap: { type: 'object', additionalProperties: { type: 'string' } }, }, additionalProperties: false, @@ -17,6 +26,11 @@ const JSON_CONFIG_SCHEMA = { type JsonPluginConfig = FromSchema; +function isPluginConfigured(plugins: Record> | undefined): boolean { + if (!plugins) return false; + return BUILTIN_PLUGIN_NAMES.json in plugins || shortenPluginName(BUILTIN_PLUGIN_NAMES.json) in plugins; +} + function isJsonFile(file: string): boolean { const lower = file.toLowerCase(); return lower.endsWith('.json') || lower.endsWith('.jsonl'); @@ -151,53 +165,66 @@ function parseJsonFile( } async function parse(context: PluginContext, options?: ParseOptions): Promise { - const cfg = (context.pluginConfig ?? {}) as JsonPluginConfig; - if (cfg.enabled === false) return null; + if (!isPluginConfigured(context.space.plugins)) return null; - const spacePath = context.space.path; - if (!existsSync(spacePath)) return null; + const cfg = (context.pluginConfig ?? {}) as JsonPluginConfig; + const targetPath = cfg.path ?? context.space.path; + if (!existsSync(targetPath)) return null; - const stat = statSync(spacePath); + const stat = statSync(targetPath); const nodes: BaseNode[] = []; const parseIssues: ParseIssue[] = []; if (stat.isFile()) { - if (!isJsonFile(spacePath)) return null; - const file = basename(spacePath); - const content = readFileSync(spacePath, 'utf-8'); + if (!isJsonFile(targetPath)) return null; + if (options?.files !== undefined) { + const absTarget = resolve(targetPath); + const touched = options.files.some((rel) => resolve(context.space.path, rel) === absTarget); + if (!touched) return null; + } + const file = basename(targetPath); + const content = readFileSync(targetPath, 'utf-8'); parseJsonFile(file, content, cfg.fieldMap, nodes, parseIssues); return { nodes, parseIssues, diagnostics: { kind: 'file' }, + ...(options?.files !== undefined ? { partial: true } : {}), }; } const resolvedSchema = resolve(context.resolvedSchemaPath); + const absTarget = resolve(targetPath); const isPartial = options?.files !== undefined; let files: string[]; if (options?.files !== undefined) { - const relevant = options.files.filter( - (rel) => isJsonFile(rel) && !rel.split(/[\\/]/).some((segment) => segment.startsWith('.')), - ); + const relevant: string[] = []; + for (const rel of options.files) { + const abs = resolve(context.space.path, rel); + const relToTarget = relative(absTarget, abs).replace(/\\/g, '/'); + if (relToTarget.startsWith('..') || isAbsolute(relToTarget)) continue; + if (!isJsonFile(relToTarget) || relToTarget.split('/').some((segment) => segment.startsWith('.'))) continue; + relevant.push(relToTarget); + } if (relevant.length === 0) return null; files = relevant.filter((rel) => { - const abs = resolve(spacePath, rel); + const abs = resolve(targetPath, rel); return abs !== resolvedSchema && existsSync(abs) && statSync(abs).isFile(); }); } else { - const found = await fg(['**/*.json', '**/*.jsonl'], { - cwd: spacePath, + const patterns = cfg.include && cfg.include.length > 0 ? cfg.include : DEFAULT_INCLUDE; + const found = await fg(patterns, { + cwd: targetPath, followSymbolicLinks: true, ignore: ['**/node_modules/**'], }); - files = found.filter((rel) => resolve(spacePath, rel) !== resolvedSchema); + files = found.filter((rel) => resolve(targetPath, rel) !== resolvedSchema); if (files.length === 0) return null; } for (const file of files) { - const content = readFileSync(join(spacePath, file), 'utf-8'); + const content = readFileSync(join(targetPath, file), 'utf-8'); parseJsonFile(file, content, cfg.fieldMap, nodes, parseIssues); } diff --git a/tests/plugins/json/read-json.test.ts b/tests/plugins/json/read-json.test.ts index bef0f30f..f89cdca5 100644 --- a/tests/plugins/json/read-json.test.ts +++ b/tests/plugins/json/read-json.test.ts @@ -75,8 +75,14 @@ describe('built-in JSON/JSONL parse plugin', () => { return createSpaceContext('test', config, { configDir: dir }); }; - it('merges markdown, JSON, and JSONL nodes in a directory and resolves cross-format links', async () => { + it('ignores JSON/JSONL files unless plugins.json is configured on the space', async () => { const result = await readSpace(makeCtx(mixedDir)); + expect(result.source).toBe('sctx-markdown'); + expect(result.nodes.map((n) => n.title)).toEqual(['RootGoal']); + }); + + it('merges markdown, JSON, and JSONL nodes when plugins.json is configured and resolves cross-format links', async () => { + const result = await readSpace(makeCtx(mixedDir, { json: {} })); expect(result.source).toBe('sctx-markdown, sctx-json'); const titles = result.nodes.map((n) => n.title).sort(); @@ -101,23 +107,37 @@ describe('built-in JSON/JSONL parse plugin', () => { ); }); - it('reads a single .jsonl file space directly', async () => { - const result = await readSpace(makeCtx(join(mixedDir, 'stream.jsonl'))); + it('reads a single .jsonl file space directly when configured', async () => { + const result = await readSpace(makeCtx(join(mixedDir, 'stream.jsonl'), { json: {} })); expect(result.source).toBe('sctx-json'); expect(result.nodes.map((n) => n.title)).toEqual(['Line One', 'Line Four']); }); - it('supports plugins.json.fieldMap and plugins.json.enabled: false', async () => { - const mappedDir = join(dir, 'mapped'); - mkdirSync(mappedDir, { recursive: true }); - writeFileSync(join(mappedDir, 'items.json'), JSON.stringify([{ kind: 'goal', title: 'Mapped Goal' }])); - - const mapped = await readSpace(makeCtx(mappedDir, { json: { fieldMap: { kind: 'type' } } })); - expect(mapped.nodes.map((n) => n.title)).toEqual(['Mapped Goal']); + it('supports path, include, and fieldMap options', async () => { + const mdDir = join(dir, 'md-only'); + const dataDir = join(dir, 'external-data'); + mkdirSync(mdDir, { recursive: true }); + mkdirSync(dataDir, { recursive: true }); + writeFileSync(join(mdDir, 'Goal.md'), ['---', 'type: goal', '---', ''].join('\n')); + writeFileSync( + join(dataDir, 'keep.jsonl'), + `${JSON.stringify({ kind: 'task', title: 'External Task', parent: '[[Goal]]' })}\n`, + ); + writeFileSync(join(dataDir, 'skip.json'), JSON.stringify({ kind: 'task', title: 'Ignored JSON' })); + + const result = await readSpace( + makeCtx(mdDir, { + json: { + path: 'external-data', + include: ['**/*.jsonl'], + fieldMap: { kind: 'type' }, + }, + }), + ); - const disabled = await readSpace(makeCtx(mappedDir, { json: { enabled: false } })); - expect(disabled.nodes).toEqual([]); - expect(disabled.source).toBe('sctx-markdown'); + expect(result.nodes.map((n) => n.title).sort()).toEqual(['External Task', 'Goal']); + const task = result.nodes.find((n) => n.title === 'External Task'); + expect(task?.resolvedParents.map((p) => String(p.id))).toEqual(['Goal.md']); }); it('updates and deletes JSON nodes during incremental refresh', async () => { @@ -126,7 +146,7 @@ describe('built-in JSON/JSONL parse plugin', () => { writeFileSync(join(watchDir, 'Goal.md'), ['---', 'type: goal', '---', ''].join('\n')); writeFileSync(join(watchDir, 'tasks.jsonl'), `${JSON.stringify({ id: 't1', type: 'task', title: 'First' })}\n`); - const ctx = makeCtx(watchDir); + const ctx = makeCtx(watchDir, { json: {} }); const initial = await readSpace(ctx); expect(initial.nodes.map((n) => n.title).sort()).toEqual(['First', 'Goal']); From dbd529942b5cf52b0375f116206031c7297ade4a Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 1 Dec 2026 09:49:02 +1100 Subject: [PATCH 3/3] Use JSON5, drop YAGNI options, and generalize parallel multi-parser dispatch --- docs/config.md | 8 +-- src/plugins/json/index.ts | 75 +++++++----------------- src/read/read-space.ts | 88 ++++++++++++++++++++-------- tests/plugins/json/read-json.test.ts | 46 ++++++--------- 4 files changed, 103 insertions(+), 114 deletions(-) diff --git a/docs/config.md b/docs/config.md index bc708929..69b41671 100644 --- a/docs/config.md +++ b/docs/config.md @@ -253,7 +253,7 @@ Controls how headings, lists and tables inside a node become embedded nodes, key ## JSON plugin config -Enable the built-in `json` plugin (`sctx-json`) per space under `plugins.json` to parse `.json` files (a single node object or an array of node objects) and `.jsonl` files (one node object per line) alongside markdown: +Enable the built-in `json` plugin (`sctx-json`) per space under `plugins.json` to parse `.json` and `.json5` files (parsed with JSON5; a single node object or an array of node objects) and `.jsonl` files (one JSON node object per line) alongside markdown: ```json { @@ -269,11 +269,9 @@ Enable the built-in `json` plugin (`sctx-json`) per space under `plugins.json` t } ``` -With an empty config (`{}`), the plugin scans the space's `path` for `**/*.json` and `**/*.jsonl`. Optional fields: +With an empty config (`{}`), the plugin scans the space's `path` for `**/*.json`, `**/*.json5`, and `**/*.jsonl`. Optional fields: -- **`path`** — directory or single `.json`/`.jsonl` file to read instead of the space's `path` (relative paths resolve from the config root). -- **`include`** — glob patterns relative to `path` (default `["**/*.json", "**/*.jsonl"]`). -- **`fieldMap`** — maps source JSON property names to canonical schema field names. +- **`path`** — directory or single `.json`/`.json5`/`.jsonl` file to read instead of the space's `path` (relative paths resolve from the config root). ## Filter views diff --git a/src/plugins/json/index.ts b/src/plugins/json/index.ts index 4c80f698..2674f3a9 100644 --- a/src/plugins/json/index.ts +++ b/src/plugins/json/index.ts @@ -2,60 +2,36 @@ import { existsSync, readFileSync, statSync } from 'node:fs'; import { basename, isAbsolute, join, relative, resolve } from 'node:path'; import fg from 'fast-glob'; import type { FromSchema } from 'json-schema-to-ts'; +import JSON5 from 'json5'; import type { BaseNode, NodeId, ParseIssue } from '../../types'; import { BUILTIN_PLUGIN_NAMES } from '../builtin-names'; -import { - type ParseOptions, - type ParseResult, - type PluginContext, - type StructuredContextPlugin, - shortenPluginName, -} from '../util'; +import type { ParseOptions, ParseResult, PluginContext, StructuredContextPlugin } from '../util'; -const DEFAULT_INCLUDE = ['**/*.json', '**/*.jsonl']; +const JSON_GLOBS = ['**/*.json', '**/*.json5', '**/*.jsonl']; const JSON_CONFIG_SCHEMA = { type: 'object', properties: { path: { type: 'string', format: 'path' }, - include: { type: 'array', items: { type: 'string', minLength: 1 } }, - fieldMap: { type: 'object', additionalProperties: { type: 'string' } }, }, additionalProperties: false, } as const; type JsonPluginConfig = FromSchema; -function isPluginConfigured(plugins: Record> | undefined): boolean { - if (!plugins) return false; - return BUILTIN_PLUGIN_NAMES.json in plugins || shortenPluginName(BUILTIN_PLUGIN_NAMES.json) in plugins; -} - function isJsonFile(file: string): boolean { const lower = file.toLowerCase(); - return lower.endsWith('.json') || lower.endsWith('.jsonl'); + return lower.endsWith('.json') || lower.endsWith('.json5') || lower.endsWith('.jsonl'); } function isPlainObject(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); } -function applyFieldMap( - data: Record, - fieldMap: Record | undefined, -): Record { - if (!fieldMap || Object.keys(fieldMap).length === 0) return data; - const result: Record = {}; - for (const [key, value] of Object.entries(data)) { - result[fieldMap[key] ?? key] = value; - } - return result; -} - function pathLinkTargets(file: string): string[] { const segments = file .replace(/\\/g, '/') - .replace(/\.jsonl?$/i, '') + .replace(/\.json[5l]?$/i, '') .split('/'); return segments.map((_, i) => segments.slice(i).join('/')); } @@ -65,7 +41,6 @@ function recordToNode( file: string, fallbackId: string, line: number, - fieldMap: Record | undefined, extraTargets: string[], parseIssues: ParseIssue[], ): BaseNode | null { @@ -79,8 +54,7 @@ function recordToNode( return null; } - const data = applyFieldMap(raw, fieldMap); - if (typeof data.type !== 'string' || data.type.trim() === '') { + if (typeof raw.type !== 'string' || raw.type.trim() === '') { parseIssues.push({ source: { file, line }, severity: 'warning', @@ -90,29 +64,23 @@ function recordToNode( return null; } - const explicitId = typeof data.id === 'string' && data.id.trim() !== '' ? data.id : undefined; + const explicitId = typeof raw.id === 'string' && raw.id.trim() !== '' ? raw.id : undefined; const id = (explicitId ?? fallbackId) as NodeId; - const explicitTitle = typeof data.title === 'string' ? data.title : undefined; - const title = explicitTitle ?? (typeof data.name === 'string' ? data.name : id); + const explicitTitle = typeof raw.title === 'string' ? raw.title : undefined; + const title = explicitTitle ?? (typeof raw.name === 'string' ? raw.name : id); return { id, title, - schemaData: { title, ...data }, + schemaData: { title, ...raw }, linkTargets: [...new Set([id, ...(explicitTitle !== undefined ? [explicitTitle] : []), ...extraTargets])], - type: data.type, + type: raw.type, source: { file, line }, - ...(typeof data.content === 'string' ? { content: data.content } : {}), + ...(typeof raw.content === 'string' ? { content: raw.content } : {}), }; } -function parseJsonFile( - file: string, - content: string, - fieldMap: Record | undefined, - nodes: BaseNode[], - parseIssues: ParseIssue[], -): void { +function parseJsonFile(file: string, content: string, nodes: BaseNode[], parseIssues: ParseIssue[]): void { const isJsonl = file.toLowerCase().endsWith('.jsonl'); if (isJsonl) { @@ -133,7 +101,7 @@ function parseJsonFile( }); continue; } - const node = recordToNode(parsed, file, `${file}:${lineNumber}`, lineNumber, fieldMap, [], parseIssues); + const node = recordToNode(parsed, file, `${file}:${lineNumber}`, lineNumber, [], parseIssues); if (node) nodes.push(node); } return; @@ -141,7 +109,7 @@ function parseJsonFile( let parsed: unknown; try { - parsed = JSON.parse(content); + parsed = JSON5.parse(content); } catch (err) { parseIssues.push({ source: { file, line: 1 }, @@ -154,19 +122,17 @@ function parseJsonFile( if (Array.isArray(parsed)) { for (let i = 0; i < parsed.length; i++) { - const node = recordToNode(parsed[i], file, `${file}#${i}`, 1, fieldMap, [], parseIssues); + const node = recordToNode(parsed[i], file, `${file}#${i}`, 1, [], parseIssues); if (node) nodes.push(node); } return; } - const node = recordToNode(parsed, file, file, 1, fieldMap, pathLinkTargets(file), parseIssues); + const node = recordToNode(parsed, file, file, 1, pathLinkTargets(file), parseIssues); if (node) nodes.push(node); } async function parse(context: PluginContext, options?: ParseOptions): Promise { - if (!isPluginConfigured(context.space.plugins)) return null; - const cfg = (context.pluginConfig ?? {}) as JsonPluginConfig; const targetPath = cfg.path ?? context.space.path; if (!existsSync(targetPath)) return null; @@ -184,7 +150,7 @@ async function parse(context: PluginContext, options?: ParseOptions): Promise 0 ? cfg.include : DEFAULT_INCLUDE; - const found = await fg(patterns, { + const found = await fg(JSON_GLOBS, { cwd: targetPath, followSymbolicLinks: true, ignore: ['**/node_modules/**'], @@ -225,7 +190,7 @@ async function parse(context: PluginContext, options?: ParseOptions): Promise 0 || result.parseIssues.length > 0 || (result.excludedPages?.length ?? 0) > 0; } -async function dispatchParse( +async function runParseBatch( + plugins: LoadedPlugin[], context: SpaceContext, options?: ParseOptions, -): Promise<{ source: string; result: ParseResult }> { - const pluginMap: Record> = context.space?.plugins ?? {}; - const loaded = await loadPlugins(pluginMap, context.configDir); +): Promise> { + const results: Array<{ name: string; result: ParseResult } | null> = new Array(plugins.length).fill(null); + let nextIndex = 0; - // Non-built-in parse plugins take precedence (first match wins). - for (const { plugin, pluginConfig } of loaded) { - if (!plugin.parse || isBuiltinPluginName(plugin.name)) continue; - const result = await plugin.parse({ ...context, pluginConfig }, options); - if (result !== null) { - return { source: plugin.name, result }; + const worker = async (): Promise => { + for (;;) { + const i = nextIndex++; + if (i >= plugins.length) return; + const { plugin, pluginConfig } = plugins[i]!; + const result = await plugin.parse!({ ...context, pluginConfig }, options); + if (result !== null) { + results[i] = { name: plugin.name, result }; + } } - } + }; - // Built-in filesystem parse plugins (e.g. markdown + json) run together and merge their results. - const matched: Array<{ name: string; result: ParseResult }> = []; - for (const { plugin, pluginConfig } of loaded) { - if (!plugin.parse || !isBuiltinPluginName(plugin.name)) continue; - const result = await plugin.parse({ ...context, pluginConfig }, options); - if (result !== null) { - matched.push({ name: plugin.name, result }); - } - } + const concurrency = Math.min(MAX_PARSE_CONCURRENCY, plugins.length); + await Promise.all(Array.from({ length: concurrency }, () => worker())); + return results.filter((entry): entry is { name: string; result: ParseResult } => entry !== null); +} - if (matched.length === 0) { - throw new Error(`No plugin handled space at: ${context.space.path}`); - } +function mergeParseResults(matched: Array<{ name: string; result: ParseResult }>): { + source: string; + result: ParseResult; +} { if (matched.length === 1) { return { source: matched[0]!.name, result: matched[0]!.result }; } @@ -70,6 +72,7 @@ async function dispatchParse( const active = matched.filter((m) => hasParsedContent(m.result)); const sourceNames = (active.length > 0 ? active : matched).map((m) => m.name); const excludedPages = matched.flatMap((m) => m.result.excludedPages ?? []); + const fieldSources = Object.assign({}, ...matched.map((m) => m.result.fieldSources ?? {})); const diagnostics = Object.assign({}, ...matched.map((m) => m.result.diagnostics)); return { @@ -78,12 +81,45 @@ async function dispatchParse( nodes: matched.flatMap((m) => m.result.nodes), parseIssues: matched.flatMap((m) => m.result.parseIssues), ...(excludedPages.length > 0 ? { excludedPages } : {}), + ...(Object.keys(fieldSources).length > 0 ? { fieldSources } : {}), diagnostics, ...(matched.every((m) => m.result.partial) ? { partial: true } : {}), }, }; } +async function dispatchParse( + context: SpaceContext, + options?: ParseOptions, +): Promise<{ source: string; result: ParseResult }> { + const pluginMap: Record> = context.space?.plugins ?? {}; + const loaded = await loadPlugins(pluginMap, context.configDir); + const configuredNames = new Set(Object.keys(pluginMap).map(normalizePluginName)); + + const parsePlugins = loaded.filter((entry) => entry.plugin.parse); + const configured = parsePlugins.filter((entry) => configuredNames.has(entry.plugin.name)); + const defaultMarkdown = parsePlugins.find((entry) => entry.plugin.name === BUILTIN_PLUGIN_NAMES.markdown); + const hasCustomConfigured = configured.some((entry) => !isBuiltinPluginName(entry.plugin.name)); + + // Configured parse plugins run in parallel and merge. Markdown is included automatically + // when no third-party parse plugin is configured, and acts as fallback if configured ones return null. + const primary = + !hasCustomConfigured && defaultMarkdown && !configuredNames.has(defaultMarkdown.plugin.name) + ? [defaultMarkdown, ...configured] + : configured; + + let matched = await runParseBatch(primary, context, options); + if (matched.length === 0 && defaultMarkdown && !primary.includes(defaultMarkdown)) { + matched = await runParseBatch([defaultMarkdown], context, options); + } + + if (matched.length === 0) { + throw new Error(`No plugin handled space at: ${context.space.path}`); + } + + return mergeParseResults(matched); +} + export async function readSpace(context: SpaceContext): Promise { const { source, result } = await dispatchParse(context); return toReadSpaceResult(source, result, context.schema.metadata); diff --git a/tests/plugins/json/read-json.test.ts b/tests/plugins/json/read-json.test.ts index f89cdca5..ec0ffbbf 100644 --- a/tests/plugins/json/read-json.test.ts +++ b/tests/plugins/json/read-json.test.ts @@ -4,17 +4,15 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { Config } from '../../../src/config'; import { readSpace, refreshReadResult } from '../../../src/read/read-space'; +import { SCHEMA_META_ID } from '../../../src/schema/metadata-contract'; import { createSpaceContext } from '../../../src/space-context'; -const META = - 'https://raw.githubusercontent.com/mindsocket/structured-context/main/schemas/generated/latest/_structured_context_schema_meta.json'; - describe('built-in JSON/JSONL parse plugin', () => { const dir = mkdtempSync(join(tmpdir(), 'sctx-json-plugin-')); afterAll(() => rmSync(dir, { recursive: true, force: true })); const schemaContent = JSON.stringify({ - $schema: META, + $schema: SCHEMA_META_ID, $id: 'sctx://json-plugin.test', $metadata: { hierarchy: { @@ -49,14 +47,15 @@ describe('built-in JSON/JSONL parse plugin', () => { writeFileSync(join(mixedDir, 'RootGoal.md'), ['---', 'type: goal', '---', ''].join('\n')); writeFileSync( join(mixedDir, 'single.json'), - JSON.stringify({ type: 'task', title: 'Single JSON Task', parent: '[[RootGoal]]' }), + `// JSON5 comments and trailing commas are supported\n{ type: 'task', title: 'Single JSON Task', parent: '[[RootGoal]]', }\n`, ); writeFileSync( - join(mixedDir, 'batch.json'), - JSON.stringify([ - { id: 'task-a', type: 'task', title: 'Batch A', parent: '[[RootGoal]]', content: 'Body text' }, - { title: 'Missing type item' }, - ]), + join(mixedDir, 'batch.json5'), + `[ + // JSON5 array of nodes + { id: 'task-a', type: 'task', title: 'Batch A', parent: '[[RootGoal]]', content: 'Body text', }, + { title: 'Missing type item', }, + ]`, ); writeFileSync( join(mixedDir, 'stream.jsonl'), @@ -75,20 +74,20 @@ describe('built-in JSON/JSONL parse plugin', () => { return createSpaceContext('test', config, { configDir: dir }); }; - it('ignores JSON/JSONL files unless plugins.json is configured on the space', async () => { + it('ignores JSON/JSON5/JSONL files unless plugins.json is configured on the space', async () => { const result = await readSpace(makeCtx(mixedDir)); expect(result.source).toBe('sctx-markdown'); expect(result.nodes.map((n) => n.title)).toEqual(['RootGoal']); }); - it('merges markdown, JSON, and JSONL nodes when plugins.json is configured and resolves cross-format links', async () => { + it('merges markdown, JSON, JSON5, and JSONL nodes when plugins.json is configured and resolves cross-format links', async () => { const result = await readSpace(makeCtx(mixedDir, { json: {} })); expect(result.source).toBe('sctx-markdown, sctx-json'); const titles = result.nodes.map((n) => n.title).sort(); expect(titles).toEqual(['Batch A', 'Line Four', 'Line One', 'RootGoal', 'Single JSON Task']); - // Cross-format links resolve between JSON/JSONL nodes and markdown/JSON targets + // Cross-format links resolve between JSON/JSON5/JSONL nodes and markdown/JSON targets const singleTask = result.nodes.find((n) => n.title === 'Single JSON Task'); expect(singleTask?.resolvedParents.map((p) => String(p.id))).toEqual(['RootGoal.md']); @@ -103,7 +102,7 @@ describe('built-in JSON/JSONL parse plugin', () => { expect.objectContaining({ type: 'parse', severity: 'error', source: { file: 'stream.jsonl', line: 3 } }), ); expect(result.parseIssues).toContainEqual( - expect.objectContaining({ type: 'no-type', severity: 'warning', source: { file: 'batch.json', line: 1 } }), + expect.objectContaining({ type: 'no-type', severity: 'warning', source: { file: 'batch.json5', line: 1 } }), ); }); @@ -113,28 +112,19 @@ describe('built-in JSON/JSONL parse plugin', () => { expect(result.nodes.map((n) => n.title)).toEqual(['Line One', 'Line Four']); }); - it('supports path, include, and fieldMap options', async () => { + it('supports plugins.json.path pointing to a separate directory', async () => { const mdDir = join(dir, 'md-only'); const dataDir = join(dir, 'external-data'); mkdirSync(mdDir, { recursive: true }); mkdirSync(dataDir, { recursive: true }); writeFileSync(join(mdDir, 'Goal.md'), ['---', 'type: goal', '---', ''].join('\n')); writeFileSync( - join(dataDir, 'keep.jsonl'), - `${JSON.stringify({ kind: 'task', title: 'External Task', parent: '[[Goal]]' })}\n`, - ); - writeFileSync(join(dataDir, 'skip.json'), JSON.stringify({ kind: 'task', title: 'Ignored JSON' })); - - const result = await readSpace( - makeCtx(mdDir, { - json: { - path: 'external-data', - include: ['**/*.jsonl'], - fieldMap: { kind: 'type' }, - }, - }), + join(dataDir, 'tasks.jsonl'), + `${JSON.stringify({ type: 'task', title: 'External Task', parent: '[[Goal]]' })}\n`, ); + const result = await readSpace(makeCtx(mdDir, { json: { path: 'external-data' } })); + expect(result.nodes.map((n) => n.title).sort()).toEqual(['External Task', 'Goal']); const task = result.nodes.find((n) => n.title === 'External Task'); expect(task?.resolvedParents.map((p) => String(p.id))).toEqual(['Goal.md']);