diff --git a/docs/config.md b/docs/config.md index 715e4cb..69b4167 100644 --- a/docs/config.md +++ b/docs/config.md @@ -251,6 +251,28 @@ 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 + +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 +{ + "spaces": [ + { + "name": "my-space", + "path": "/path/to/space", + "plugins": { + "json": {} + } + } + ] +} +``` + +With an empty config (`{}`), the plugin scans the space's `path` for `**/*.json`, `**/*.json5`, and `**/*.jsonl`. Optional fields: + +- **`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 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 bb4e37e..f8ff34a 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 1f327e3..6711e43 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 0000000..2674f3a --- /dev/null +++ b/src/plugins/json/index.ts @@ -0,0 +1,208 @@ +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, ParseResult, PluginContext, StructuredContextPlugin } from '../util'; + +const JSON_GLOBS = ['**/*.json', '**/*.json5', '**/*.jsonl']; + +const JSON_CONFIG_SCHEMA = { + type: 'object', + properties: { + path: { type: 'string', format: 'path' }, + }, + additionalProperties: false, +} as const; + +type JsonPluginConfig = FromSchema; + +function isJsonFile(file: string): boolean { + const lower = file.toLowerCase(); + 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 pathLinkTargets(file: string): string[] { + const segments = file + .replace(/\\/g, '/') + .replace(/\.json[5l]?$/i, '') + .split('/'); + return segments.map((_, i) => segments.slice(i).join('/')); +} + +function recordToNode( + raw: unknown, + file: string, + fallbackId: string, + line: number, + 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; + } + + if (typeof raw.type !== 'string' || raw.type.trim() === '') { + parseIssues.push({ + source: { file, line }, + severity: 'warning', + type: 'no-type', + message: 'No type specified', + }); + return null; + } + + const explicitId = typeof raw.id === 'string' && raw.id.trim() !== '' ? raw.id : undefined; + const id = (explicitId ?? fallbackId) as NodeId; + const explicitTitle = typeof raw.title === 'string' ? raw.title : undefined; + const title = explicitTitle ?? (typeof raw.name === 'string' ? raw.name : id); + + return { + id, + title, + schemaData: { title, ...raw }, + linkTargets: [...new Set([id, ...(explicitTitle !== undefined ? [explicitTitle] : []), ...extraTargets])], + type: raw.type, + source: { file, line }, + ...(typeof raw.content === 'string' ? { content: raw.content } : {}), + }; +} + +function parseJsonFile(file: string, content: string, 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, [], parseIssues); + if (node) nodes.push(node); + } + return; + } + + let parsed: unknown; + try { + parsed = JSON5.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, [], parseIssues); + if (node) nodes.push(node); + } + return; + } + + const node = recordToNode(parsed, file, file, 1, pathLinkTargets(file), parseIssues); + if (node) nodes.push(node); +} + +async function parse(context: PluginContext, options?: ParseOptions): Promise { + const cfg = (context.pluginConfig ?? {}) as JsonPluginConfig; + const targetPath = cfg.path ?? context.space.path; + if (!existsSync(targetPath)) return null; + + const stat = statSync(targetPath); + const nodes: BaseNode[] = []; + const parseIssues: ParseIssue[] = []; + + if (stat.isFile()) { + 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, 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: 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(targetPath, rel); + return abs !== resolvedSchema && existsSync(abs) && statSync(abs).isFile(); + }); + } else { + const found = await fg(JSON_GLOBS, { + cwd: targetPath, + followSymbolicLinks: true, + ignore: ['**/node_modules/**'], + }); + files = found.filter((rel) => resolve(targetPath, rel) !== resolvedSchema); + if (files.length === 0) return null; + } + + for (const file of files) { + const content = readFileSync(join(targetPath, file), 'utf-8'); + parseJsonFile(file, content, 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 cad298d..1564ce0 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 6227e2d..c0ffa4a 100644 --- a/src/read/read-space.ts +++ b/src/read/read-space.ts @@ -1,8 +1,11 @@ -import { loadPlugins } from '../plugins/loader'; -import type { ParseOptions, ParseResult } from '../plugins/util'; +import { BUILTIN_PLUGIN_NAMES, isBuiltinPluginName } from '../plugins/builtin-names'; +import { type LoadedPlugin, loadPlugins } from '../plugins/loader'; +import { normalizePluginName, type ParseOptions, type ParseResult } from '../plugins/util'; import type { BaseNode, ReadSpaceResult, SpaceContext } from '../types'; import { resolveGraphEdges } from './resolve-graph-edges'; +const MAX_PARSE_CONCURRENCY = 4; + function normalizeFile(file: string): string { return file.replace(/\\/g, '/').replace(/^\.\//, ''); } @@ -29,22 +32,92 @@ function toReadSpaceResult( }; } +function hasParsedContent(result: ParseResult): boolean { + return result.nodes.length > 0 || result.parseIssues.length > 0 || (result.excludedPages?.length ?? 0) > 0; +} + +async function runParseBatch( + plugins: LoadedPlugin[], + context: SpaceContext, + options?: ParseOptions, +): Promise> { + const results: Array<{ name: string; result: ParseResult } | null> = new Array(plugins.length).fill(null); + let nextIndex = 0; + + 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 }; + } + } + }; + + 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); +} + +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 }; + } + + 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 { + source: sourceNames.join(', '), + result: { + 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)); - for (const { plugin, pluginConfig } of loaded) { - if (!plugin.parse) continue; - const result = await plugin.parse({ ...context, pluginConfig }, options); - if (result !== null) { - return { source: plugin.name, result }; - } + 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}`); } - throw new Error(`No plugin handled space at: ${context.space.path}`); + return mergeParseResults(matched); } 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 0000000..ec0ffbb --- /dev/null +++ b/tests/plugins/json/read-json.test.ts @@ -0,0 +1,151 @@ +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 { SCHEMA_META_ID } from '../../../src/schema/metadata-contract'; +import { createSpaceContext } from '../../../src/space-context'; + +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: SCHEMA_META_ID, + $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'), + `// JSON5 comments and trailing commas are supported\n{ type: 'task', title: 'Single JSON Task', parent: '[[RootGoal]]', }\n`, + ); + writeFileSync( + 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'), + [ + 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('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, 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/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']); + + 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.json5', line: 1 } }), + ); + }); + + 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.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, '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']); + }); + + 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, { json: {} }); + 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 8f002d5..da587b3 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({});