From 0ef7c804cae6d6f4dc1e04782dff5f87e82af03b Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Mon, 30 Nov 2026 23:02:26 +1100 Subject: [PATCH 1/3] fix: close remaining incremental read and watch validation gaps (#259) --- src/commands/validate.ts | 151 ++++++++++++++++--------- src/index.ts | 11 +- src/plugins/markdown/read-space.ts | 1 + src/plugins/util.ts | 5 +- tests/read/refresh-read-result.test.ts | 21 ++++ tests/validate/watch-validate.test.ts | 123 ++++++++++++++++++++ 6 files changed, 253 insertions(+), 59 deletions(-) create mode 100644 tests/validate/watch-validate.test.ts diff --git a/src/commands/validate.ts b/src/commands/validate.ts index e72a702..d428c1f 100644 --- a/src/commands/validate.ts +++ b/src/commands/validate.ts @@ -21,10 +21,9 @@ function ofKind(result: ValidationResult, kin return result.issues.filter((issue): issue is Extract => issue.kind === kind); } -export async function validate( - context: SpaceContext, - options: { json?: boolean } & ValidateSpaceOptions = {}, -): Promise { +export type ValidateCommandOptions = { json?: boolean } & ValidateSpaceOptions; + +export async function validate(context: SpaceContext, options: ValidateCommandOptions = {}): Promise { const result = await validateSpace(context, options); const errorCount = result.issues.filter((issue) => issue.severity === 'error').length; @@ -192,7 +191,90 @@ export async function validate( return errorCount === 0 ? 0 : 1; } -export async function watchValidate(context: SpaceContext): Promise { +export interface WatchSessionDeps { + read?: typeof readSpace; + refresh?: typeof refreshReadResult; + runValidate?: typeof validate; + reloadContext?: (spaceName: string) => SpaceContext; + onBeforeRevalidate?: (filePath: string, action: string) => void; +} + +/** + * Serialized state machine for `watchValidate`: holds the latest `SpaceContext` and + * `ReadSpaceResult`, forwards CLI validate options on every run, and queues change events + * so concurrent filesystem events (e.g. rename = unlink + add) cannot race on `refreshReadResult`. + */ +export function createWatchSession( + context: SpaceContext, + options: ValidateCommandOptions = {}, + deps: WatchSessionDeps = {}, +) { + const read = deps.read ?? readSpace; + const refresh = deps.refresh ?? refreshReadResult; + const runValidate = deps.runValidate ?? validate; + const reloadContext = deps.reloadContext ?? ((name) => createSpaceContext(name, loadConfig())); + const onBeforeRevalidate = deps.onBeforeRevalidate; + + let exitCode = 0; + let currentContext = context; + let currentReadResult: ReadSpaceResult | undefined; + const resolvedSpacePath = resolve(context.space.path); + + const innerValidate = async (changedSpaceFile?: string) => { + try { + if (changedSpaceFile && currentReadResult) { + currentReadResult = await refresh(currentContext, currentReadResult, [changedSpaceFile]); + } else { + currentReadResult = await read(currentContext); + } + exitCode = await runValidate(currentContext, { ...options, readResult: currentReadResult }); + } catch (error) { + console.error(`āŒ Error during validation: ${error instanceof Error ? error.message : String(error)}`); + exitCode = 2; + } + }; + + let queue = Promise.resolve(); + const enqueue = (task: () => Promise): Promise => { + queue = queue.then(task, task); + return queue; + }; + + const runInitial = () => enqueue(() => innerValidate()); + + const handleChange = (filePath: string, action: string) => + enqueue(async () => { + onBeforeRevalidate?.(filePath, action); + const absFile = resolve(filePath); + const relToSpace = relative(resolvedSpacePath, absFile); + const isInSpace = relToSpace !== '' && !relToSpace.startsWith('..') && !isAbsolute(relToSpace); + if (isInSpace) { + await innerValidate(relToSpace.replace(/\\/g, '/')); + } else if (absFile === resolvedSpacePath) { + // Single-file space (space_on_a_page): re-read without reloading config/schema. + await innerValidate(); + } else { + // Config or schema changed: rebuild context and do a full read. + try { + currentContext = reloadContext(context.space.name); + } catch (error) { + console.error(`āŒ Error reloading config/schema: ${error instanceof Error ? error.message : String(error)}`); + exitCode = 2; + return; + } + currentReadResult = undefined; + await innerValidate(); + } + }); + + return { + runInitial, + handleChange, + getExitCode: () => exitCode, + }; +} + +export async function watchValidate(context: SpaceContext, options: ValidateCommandOptions = {}): Promise { const spacePath = context.space.path; const schemaPath = context.resolvedSchemaPath; const configFiles = Array.from(getConfigSourceFiles()); @@ -216,25 +298,13 @@ export async function watchValidate(context: SpaceContext): Promise { process.stdout.write('\x1b[s'); - let exitCode = 0; - let currentContext = context; - let currentReadResult: ReadSpaceResult | undefined; - const resolvedSpacePath = resolve(spacePath); - - const innerValidate = async (changedSpaceFile?: string) => { - try { - if (changedSpaceFile && currentReadResult) { - currentReadResult = await refreshReadResult(currentContext, currentReadResult, [changedSpaceFile]); - } else { - currentReadResult = await readSpace(currentContext); - } - exitCode = await validate(currentContext, { readResult: currentReadResult }); - } catch (error) { - console.error(`āŒ Error during validation: ${error instanceof Error ? error.message : String(error)}`); - exitCode = 2; - } - }; - await innerValidate(); + const session = createWatchSession(context, options, { + onBeforeRevalidate: (filePath, action) => { + process.stdout.write('\x1b[u\x1b[0J'); + console.log(`šŸ”„ ${filePath} ${action}, re-validating...\n`); + }, + }); + await session.runInitial(); const watchPaths = [...configFiles, ...schemaDirs, spacePath]; @@ -246,34 +316,9 @@ export async function watchValidate(context: SpaceContext): Promise { }, }); - const handleFileChange = async (filePath: string, action: string) => { - process.stdout.write('\x1b[u\x1b[0J'); - console.log(`šŸ”„ ${filePath} ${action}, re-validating...\n`); - const absFile = resolve(filePath); - const relToSpace = relative(resolvedSpacePath, absFile); - const isInSpace = relToSpace !== '' && !relToSpace.startsWith('..') && !isAbsolute(relToSpace); - if (isInSpace) { - await innerValidate(relToSpace.replace(/\\/g, '/')); - } else if (absFile === resolvedSpacePath) { - // Single-file space (space_on_a_page): re-read without reloading config/schema. - await innerValidate(); - } else { - // Config or schema changed: rebuild context and do a full read. - try { - currentContext = createSpaceContext(context.space.name, loadConfig()); - } catch (error) { - console.error(`āŒ Error reloading config/schema: ${error instanceof Error ? error.message : String(error)}`); - exitCode = 2; - return; - } - currentReadResult = undefined; - await innerValidate(); - } - }; - - watcher.on('add', (path) => handleFileChange(path, 'added')); - watcher.on('change', (path) => handleFileChange(path, 'changed')); - watcher.on('unlink', (path) => handleFileChange(path, 'removed')); + watcher.on('add', (path) => void session.handleChange(path, 'added')); + watcher.on('change', (path) => void session.handleChange(path, 'changed')); + watcher.on('unlink', (path) => void session.handleChange(path, 'removed')); watcher.on('error', (error) => { console.error(`Watcher error: ${error}`); }); @@ -282,7 +327,7 @@ export async function watchValidate(context: SpaceContext): Promise { process.on('SIGINT', () => { console.log('\n\nšŸ‘‹ Stopping watch mode...'); watcher.close(); - process.exit(exitCode); + process.exit(session.getExitCode()); }); process.on('uncaughtException', reject); }); diff --git a/src/index.ts b/src/index.ts index 1b0d4a8..e404d93 100755 --- a/src/index.ts +++ b/src/index.ts @@ -118,14 +118,15 @@ addValidationOptions( ), ).action(async (spaceName, options) => { const context = buildSpaceContext(spaceName); + const validateOptions = { + ...commonValidateCliOptions(options), + depth: options.depth, + }; if (options.watch) { - await watchValidate(context); + await watchValidate(context, validateOptions); } else { // exitCode rather than process.exit(): exiting straight away can cut off large piped output - process.exitCode = await validate(context, { - ...commonValidateCliOptions(options), - depth: options.depth, - }); + process.exitCode = await validate(context, validateOptions); } }); diff --git a/src/plugins/markdown/read-space.ts b/src/plugins/markdown/read-space.ts index e245cc2..329ab01 100644 --- a/src/plugins/markdown/read-space.ts +++ b/src/plugins/markdown/read-space.ts @@ -112,6 +112,7 @@ export async function readSpaceDirectory( const abs = resolve(directory, file); const rel = relative(directory, abs); if (rel.startsWith('..') || isAbsolute(rel)) return false; + if (rel.split(/[\\/]/).some((segment) => segment.startsWith('.'))) return false; return existsSync(abs) && statSync(abs).isFile(); }) : await fg('**/*.md', { cwd: directory, followSymbolicLinks: true }); diff --git a/src/plugins/util.ts b/src/plugins/util.ts index 97ea560..f158a21 100644 --- a/src/plugins/util.ts +++ b/src/plugins/util.ts @@ -34,7 +34,10 @@ export type PluginContext = SpaceContext & { persistConfig?: (updates: Record) => void; /** Validate the whole space and return every issue found, of every severity. */ validate?: ( - options?: Pick, + options?: Pick< + ValidateSpaceOptions, + 'includeGated' | 'ruleFilter' | 'semantic' | 'depth' | 'cacheMode' | 'cacheDir' + >, ) => Promise; /** The graph being rendered, in the space graph format. */ exportGraph?: () => SpaceGraphData; diff --git a/tests/read/refresh-read-result.test.ts b/tests/read/refresh-read-result.test.ts index 92cbc08..450cf86 100644 --- a/tests/read/refresh-read-result.test.ts +++ b/tests/read/refresh-read-result.test.ts @@ -330,4 +330,25 @@ describe('refreshReadResult', () => { expect(refreshed.nodes).toHaveLength(2); await expectMatchesFullRead(context, refreshed); }); + + test('ignores dot-prefixed paths during partial refresh to match full read', async () => { + const { spaceDir, context } = makeTempSpace({ + 'vision.md': '---\ntype: vision\ntitle: Our Vision\nstatus: active\n---\n', + }); + const initial = await readSpace(context); + + for (const rel of ['.obsidian/note.md', '.trash/old.md', 'sub/.hidden.md']) { + const full = join(spaceDir, rel); + mkdirSync(join(full, '..'), { recursive: true }); + writeFileSync(full, '---\ntype: vision\ntitle: Hidden\nstatus: active\n---\n', 'utf-8'); + } + + const refreshed = await refreshReadResult(context, initial, [ + '.obsidian/note.md', + '.trash/old.md', + 'sub/.hidden.md', + ]); + expect(refreshed.nodes.map((n) => String(n.id))).toEqual(['vision.md']); + await expectMatchesFullRead(context, refreshed); + }); }); diff --git a/tests/validate/watch-validate.test.ts b/tests/validate/watch-validate.test.ts new file mode 100644 index 0000000..cb353f5 --- /dev/null +++ b/tests/validate/watch-validate.test.ts @@ -0,0 +1,123 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createWatchSession, type ValidateCommandOptions } from '../../src/commands/validate'; +import type { Config } from '../../src/config'; +import { createSpaceContext } from '../../src/space-context'; +import type { ReadSpaceResult } from '../../src/types'; + +const tempDirs: string[] = []; + +function makeSpace() { + const root = mkdtempSync(join(tmpdir(), 'sctx-watch-')); + tempDirs.push(root); + const spaceDir = join(root, 'space'); + mkdirSync(spaceDir, { recursive: true }); + writeFileSync(join(spaceDir, 'vision.md'), '---\ntype: vision\ntitle: V1\nstatus: active\n---\n', 'utf-8'); + const config: Config = { + spaces: [{ name: 'test', path: spaceDir, schema: 'strategy_general.json' }], + }; + return { spaceDir, context: createSpaceContext('test', config, { configDir: root }) }; +} + +function fakeReadResult(tag: string): ReadSpaceResult { + return { + nodes: [], + parseIssues: [], + unresolvedRefs: [], + unresolvedContentLinks: [], + diagnostics: { tag }, + source: 'fake', + }; +} + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +describe('createWatchSession', () => { + test('forwards all validate options on initial run and file changes', async () => { + const { spaceDir, context } = makeSpace(); + const seenOptions: ValidateCommandOptions[] = []; + const options: ValidateCommandOptions = { + json: true, + semantic: 'openrouter-jev', + cacheMode: 'only', + depth: 2, + includeGated: true, + ruleFilter: ['severity=error'], + }; + + const session = createWatchSession(context, options, { + read: async () => fakeReadResult('initial'), + refresh: async (_ctx, _prev, files) => fakeReadResult(`refreshed:${files.join(',')}`), + runValidate: async (_ctx, opts) => { + seenOptions.push(opts ?? {}); + return 0; + }, + }); + + await session.runInitial(); + await session.handleChange(join(spaceDir, 'vision.md'), 'changed'); + + expect(seenOptions).toHaveLength(2); + for (const opts of seenOptions) { + expect(opts.json).toBe(true); + expect(opts.semantic).toBe('openrouter-jev'); + expect(opts.cacheMode).toBe('only'); + expect(opts.depth).toBe(2); + expect(opts.includeGated).toBe(true); + expect(opts.ruleFilter).toEqual(['severity=error']); + } + expect(seenOptions[0]!.readResult?.diagnostics.tag).toBe('initial'); + expect(seenOptions[1]!.readResult?.diagnostics.tag).toBe('refreshed:vision.md'); + }); + + test('serializes concurrent file change events so refreshReadResult does not race', async () => { + const { spaceDir, context } = makeSpace(); + const refreshLog: Array<{ prevTag: string; files: string[] }> = []; + let releaseFirstRefresh!: () => void; + const firstRefreshPaused = new Promise((resolve) => { + releaseFirstRefresh = resolve; + }); + + const session = createWatchSession( + context, + {}, + { + read: async () => fakeReadResult('v0'), + refresh: async (_ctx, prev, files) => { + const prevTag = String(prev.diagnostics.tag); + refreshLog.push({ prevTag, files }); + if (refreshLog.length === 1) { + await firstRefreshPaused; + } + return fakeReadResult(`${prevTag}->${files.join(',')}`); + }, + runValidate: async () => 0, + }, + ); + + await session.runInitial(); + + // Fire unlink + add simultaneously (rename) + const first = session.handleChange(join(spaceDir, 'old.md'), 'removed'); + const second = session.handleChange(join(spaceDir, 'new.md'), 'added'); + + // Let microtasks flush; second refresh must not have started while first is in flight + await Promise.resolve(); + expect(refreshLog).toEqual([{ prevTag: 'v0', files: ['old.md'] }]); + + releaseFirstRefresh(); + await Promise.all([first, second]); + + // Second refresh must see the result produced by the first refresh, not stale v0 + expect(refreshLog).toEqual([ + { prevTag: 'v0', files: ['old.md'] }, + { prevTag: 'v0->old.md', files: ['new.md'] }, + ]); + }); +}); From d08052fb1e3b677a22f1a71747e8f7718f533818 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 1 Dec 2026 00:09:49 +1100 Subject: [PATCH 2/3] chore: unexport WatchSessionDeps and bump chokidar to 6.0.0 --- bun.lock | 10 +++++++--- package.json | 2 +- src/commands/validate.ts | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/bun.lock b/bun.lock index 473b397..b0c3c07 100644 --- a/bun.lock +++ b/bun.lock @@ -7,7 +7,7 @@ "dependencies": { "ajv": "^8.20.0", "ajv-formats": "^3.0.1", - "chokidar": "^5.0.0", + "chokidar": "^6.0.0", "commander": "^15.0.0", "fast-glob": "^3.3.3", "gray-matter": "^4.0.3", @@ -185,7 +185,7 @@ "character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="], - "chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], + "chokidar": ["chokidar@6.0.0", "", { "dependencies": { "readdirp": "^5.1.1" } }, "sha512-Ec2Z7wpcKBiMpR7DxteoqS/sq5G5d2A4fpxzPv6+fD7xNNdrTghn7L11YwV5EN1B3i72Erc3XVT5FkWIDx90+A=="], "cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], @@ -491,7 +491,7 @@ "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], - "readdirp": ["readdirp@5.0.0", "", {}, "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ=="], + "readdirp": ["readdirp@5.1.1", "", {}, "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA=="], "remark-gfm": ["remark-gfm@4.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="], @@ -607,6 +607,10 @@ "mdast-util-find-and-replace/unist-util-visit-parents": ["unist-util-visit-parents@6.0.2", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0" } }, "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ=="], + "structured-context/chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], + "gray-matter/js-yaml/argparse": ["argparse@1.0.10", "", { "dependencies": { "sprintf-js": "~1.0.2" } }, "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg=="], + + "structured-context/chokidar/readdirp": ["readdirp@5.0.0", "", {}, "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ=="], } } diff --git a/package.json b/package.json index 4d63954..9c9b3d9 100644 --- a/package.json +++ b/package.json @@ -75,7 +75,7 @@ "dependencies": { "ajv": "^8.20.0", "ajv-formats": "^3.0.1", - "chokidar": "^5.0.0", + "chokidar": "^6.0.0", "commander": "^15.0.0", "fast-glob": "^3.3.3", "gray-matter": "^4.0.3", diff --git a/src/commands/validate.ts b/src/commands/validate.ts index d428c1f..643d7d4 100644 --- a/src/commands/validate.ts +++ b/src/commands/validate.ts @@ -191,7 +191,7 @@ export async function validate(context: SpaceContext, options: ValidateCommandOp return errorCount === 0 ? 0 : 1; } -export interface WatchSessionDeps { +interface WatchSessionDeps { read?: typeof readSpace; refresh?: typeof refreshReadResult; runValidate?: typeof validate; From ddd8885dff0e172bbc99e5261dfb8377b14f1532 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 1 Dec 2026 00:27:38 +1100 Subject: [PATCH 3/3] chore: unexport ValidateCommandOptions --- src/commands/validate.ts | 2 +- tests/validate/watch-validate.test.ts | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/commands/validate.ts b/src/commands/validate.ts index 643d7d4..2dd137e 100644 --- a/src/commands/validate.ts +++ b/src/commands/validate.ts @@ -21,7 +21,7 @@ function ofKind(result: ValidationResult, kin return result.issues.filter((issue): issue is Extract => issue.kind === kind); } -export type ValidateCommandOptions = { json?: boolean } & ValidateSpaceOptions; +type ValidateCommandOptions = { json?: boolean } & ValidateSpaceOptions; export async function validate(context: SpaceContext, options: ValidateCommandOptions = {}): Promise { const result = await validateSpace(context, options); diff --git a/tests/validate/watch-validate.test.ts b/tests/validate/watch-validate.test.ts index cb353f5..abd482e 100644 --- a/tests/validate/watch-validate.test.ts +++ b/tests/validate/watch-validate.test.ts @@ -2,7 +2,10 @@ import { afterEach, describe, expect, test } from 'bun:test'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { createWatchSession, type ValidateCommandOptions } from '../../src/commands/validate'; +import { createWatchSession } from '../../src/commands/validate'; + +type WatchValidateOptions = NonNullable[1]>; + import type { Config } from '../../src/config'; import { createSpaceContext } from '../../src/space-context'; import type { ReadSpaceResult } from '../../src/types'; @@ -41,8 +44,8 @@ afterEach(() => { describe('createWatchSession', () => { test('forwards all validate options on initial run and file changes', async () => { const { spaceDir, context } = makeSpace(); - const seenOptions: ValidateCommandOptions[] = []; - const options: ValidateCommandOptions = { + const seenOptions: WatchValidateOptions[] = []; + const options: WatchValidateOptions = { json: true, semantic: 'openrouter-jev', cacheMode: 'only',